Stage 1: Getting Started

Getting Started · Lesson 04

Add Interactivity with JavaScript

DOM manipulation, events and a dark-mode toggle that makes your page respond to the people using it.

Getting Started11 min readFree lesson

Audience: Students who have completed Lessons 1–3 (HTML/CSS basics, able to git push) Time: 1–2 hour workshop What you need: the index.html you built in Lesson 1, VS Code, a browser (Chrome recommended) What you'll end up with: a living homepage that reacts when you click buttons and updates in real time


The Lesson at a Glance

Time Step What you learn
0:00 ~ 0:15 1. What is JavaScript? How it differs from HTML/CSS
0:15 ~ 0:30 2. First code — console and alert Where code runs
0:30 ~ 0:55 3. Variables, data types, operators Core syntax
0:55 ~ 1:20 4. Reacting to button clicks (DOM manipulation) Real interaction
1:20 ~ 1:45 5. Conditionals, loops, functions Control flow
1:45 ~ 1:55 6. Exercise: dark mode toggle A small end-to-end project
1:55 ~ 2:00 7. Wrapping up & what's next Where to go from here

1. What is JavaScript? (15 min)

How HTML, CSS, and JavaScript split the work

If you compare the page you have built so far to a person:

Technology Role Analogy
HTML Structure Skeleton (the body's frame)
CSS Design Clothes, makeup (appearance)
JavaScript Behavior Muscles, nerves (movement)

A page with only HTML/CSS is a photo; add JavaScript and it becomes video.

What can you do with JavaScript?

  • Show a message when a button is clicked
  • Live preview as you type in an input field
  • Dark mode toggle
  • Slide shows, carousels
  • Fetch data from a server and draw it on the screen (weather, news, social media)
  • Games, chatbots, drawing apps...

Almost every dynamic feature on today's web is JavaScript.

Wait — aren't "Java" and "JavaScript" the same thing?

No. They are completely different languages.

🍔 A famous analogy: "Java is to JavaScript as ham is to hamster" (as different as ham is from hamster)

Java was created by Sun Microsystems in 1995, and JavaScript by Netscape the same year — they are separate languages. The similar name was a marketing accident. Don't confuse them.


2. First Code — Console and alert (15 min)

2-1. Opening the browser developer tools

In the Chrome browser, press F12 (on Mac, Cmd + Option + I). A panel opens on one side of the screen. Click the Console tab at the top.

💡 Developer tools work on every website. Google, or anywhere else — just press F12.

2-2. Typing your first code in the console

In the console input field:

console.log("Hello, JavaScript!");

Press Enter. The result appears in grey text. You just ran code. No compiling, no build, no saving.

Try some other things:

1 + 1
"Hello" + " there"
2026 - 1995

2-3. alert — popping up a dialog on screen

alert("Welcome!");

A popup appears at the top of the browser.

2-4. Running JavaScript from an HTML file

The console is for practice; in real projects you embed JavaScript in the HTML.

Right before </body> in index.html, add:

    <script>
        console.log("The page has loaded!");
        alert("Welcome to my page");
    </script>
</body>

Save, then refresh the browser — the popup appears, and the message is also printed to the console.

⚠️ The standard practice is to put the <script> tag directly above </body>, so that the HTML is fully rendered before the JavaScript runs.


3. Variables, Data Types, and Operators (25 min)

3-1. Variables — giving a value a name

let name = "Alex Kim";
let age = 25;
let isStudent = true;

console.log(name);      // "Alex Kim"
console.log(age + 5);   // 30

let is the keyword that "creates a variable". = does not mean "equals" — it means "put in".

let count = 0;
count = count + 1;     // count is now 1
count = count + 1;     // count is now 2

3-2. Values that don't change are const

const PI = 3.14;
const myName = "Alex";

PI = 4;  // ❌ Error! const can't be reassigned

💡 Practical tip: Start with const, and use let only when you really need to change the value. It's a safer habit.

3-3. Basic data types

Type Example Description
Number 25, 3.14, -100 Both integers and decimals
String "Hello", 'hello' Wrapped in quotes
Boolean true, false True/false
Array [1, 2, 3], ["apple", "pear"] A group of values
Object {name: "Alex", age: 25} Key-value pairs
undefined undefined No value
null null Intentionally empty

3-4. Operators

// Arithmetic
10 + 3      // 13
10 - 3      // 7
10 * 3      // 30
10 / 3      // 3.333...
10 % 3      // 1 (remainder)

// String concatenation
"Hello" + " " + "Alex"   // "Hello Alex"

// Comparison (returns true / false)
5 > 3       // true
5 === 5     // true (strictly equal)
5 !== 3     // true (not equal)

// Logical
true && false   // false (AND)
true || false   // true (OR)
!true           // false (NOT)

⚠️ Important: Always use === (three equals signs) for comparisons. == (two equals signs) has many traps because of type conversion.

3-5. Working with arrays

let fruits = ["apple", "pear", "strawberry"];

console.log(fruits[0]);         // "apple" (starts at 0!)
console.log(fruits.length);     // 3
fruits.push("grape");            // add to the end
console.log(fruits);             // ["apple", "pear", "strawberry", "grape"]

3-6. Working with objects

let person = {
    name: "Alex Kim",
    age: 25,
    hobby: "coding"
};

console.log(person.name);       // "Alex Kim"
console.log(person.age);        // 25
person.age = 26;                // update
person.email = "[email protected]";        // add a new property

4. Reacting to Button Clicks — DOM Manipulation (25 min) ⭐ Highlight

This is where truly interactive web pages begin.

4-1. What is the DOM?

The browser reads the HTML and converts it into an object structure that JavaScript can work with, called the DOM (Document Object Model).

<h1 id="title">Hello</h1>

This HTML is handled like this in JavaScript:

const title = document.getElementById("title");
title.textContent = "Nice to meet you";  // the text changes!
title.style.color = "red";        // the color changes too!

4-2. Finding elements

// Find by id (most common)
document.getElementById("title")

// Find by class (several elements)
document.querySelectorAll(".card")

// Find only the first match with a CSS selector
document.querySelector("h1")
document.querySelector(".card p")

4-3. Changing elements

const el = document.getElementById("title");

el.textContent = "New text";      // change the text
el.innerHTML = "<b>Bold</b>";    // change the HTML itself
el.style.color = "blue";        // inline style
el.classList.add("active");     // add a CSS class
el.classList.remove("hidden");
el.classList.toggle("dark");    // remove if present, add if absent

4-4. Events — reacting to user actions

const button = document.getElementById("myButton");

button.addEventListener("click", function() {
    alert("The button was clicked!");
});

addEventListener("click", ...) = "when this button is clicked, run this function"

Frequently used events:

Event When it fires
click When something is clicked
mouseover When the mouse moves over an element
mouseout When the mouse leaves an element
keydown When a key is pressed
input Typing into an input field
submit Submitting a form

4-5. Exercise: click counter

Add this to index.html:

<div class="card">
    <h2>Click Counter</h2>
    <p>Number of clicks: <span id="count">0</span></p>
    <button id="clickBtn">Click me</button>
</div>

<script>
    let count = 0;
    const btn = document.getElementById("clickBtn");
    const display = document.getElementById("count");

    btn.addEventListener("click", function() {
        count = count + 1;
        display.textContent = count;
    });
</script>

Save → refresh → press the button. The number goes up! 🎉

Your page has reacted for the first time.


5. Conditionals, Loops, and Functions (25 min)

5-1. if conditionals

const age = 20;

if (age >= 18) {
    console.log("You are an adult");
} else {
    console.log("You are a minor");
}

Multiple conditions:

const score = 85;

if (score >= 90) {
    console.log("A");
} else if (score >= 80) {
    console.log("B");
} else if (score >= 70) {
    console.log("C");
} else {
    console.log("F");
}

5-2. for loops

for (let i = 0; i < 5; i++) {
    console.log("Repeat " + i);
}
// Repeat 0
// Repeat 1
// Repeat 2
// Repeat 3
// Repeat 4

Iterating over an array:

const fruits = ["apple", "pear", "strawberry"];

for (const fruit of fruits) {
    console.log(fruit);
}

5-3. Functions — grouping code

To avoid writing the same code many times, you group it into a function.

function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("Alex"));      // "Hello, Alex!"
console.log(greet("Sam"));       // "Hello, Sam!"

Arrow functions (more common these days):

const greet = (name) => {
    return "Hello, " + name + "!";
};

5-4. Putting it together

function calculateGrade(score) {
    if (score >= 90) return "A";
    if (score >= 80) return "B";
    if (score >= 70) return "C";
    return "F";
}

const scores = [95, 82, 71, 60];
for (const s of scores) {
    console.log(s + " points → " + calculateGrade(s));
}

6. Mini Project: Dark Mode Toggle (10 min)

This is a small project that uses everything you have learned so far.

6-1. Add the HTML

Somewhere sensible inside <body>:

<button id="darkBtn">🌙 Dark mode</button>

6-2. Add the CSS (inside <style>)

body.dark {
    background: #1a1a1a;
    color: #f3f4f6;
}
body.dark .card {
    background: #2a2a2a;
}
body.dark h1 {
    color: #93c5fd;
}

6-3. Add the JavaScript (inside <script>)

const darkBtn = document.getElementById("darkBtn");

darkBtn.addEventListener("click", function() {
    document.body.classList.toggle("dark");

    if (document.body.classList.contains("dark")) {
        darkBtn.textContent = "☀️ Light mode";
    } else {
        darkBtn.textContent = "🌙 Dark mode";
    }
});

Save → refresh → click the button → the whole page changes in an instant.

6-4. Push and you're done

git add .
git commit -m "Add dark mode toggle"
git push

Vercel deploys it automatically. Send the link to a friend and say "try pressing the button".


7. Wrapping Up & What's Next (5 min)

What you learned today

Variables (let, const)
   ↓
Types (number, string, array, object)
   ↓
DOM manipulation (getElementById, textContent, classList)
   ↓
Events (addEventListener)
   ↓
Conditionals / loops / functions
   ↓
Mini project (dark mode toggle)

If all of this has sunk in, you can build almost any simple interaction.

  • Form validation
  • A todo list
  • A calculator
  • A simple game (tic-tac-toe level)

You can take on all of them.

What would be good to learn next

When What Why
Next week fetch / API calls Get data from a server (weather, news)
After that localStorage Storage that survives a refresh
In a month React / Next.js Build large apps in an organized way
In two months TypeScript Safe JavaScript

Recommended learning resources (all free)

One last word

JavaScript is the most widely used language in the world. The web, of course, but also mobile apps (React Native), desktop apps (Electron), servers (Node.js), and even spacecraft control.

The syntax you learned today is the starting point for everything in JavaScript that comes next. Don't try to memorize it all at once — look things up as you build what you want to build. That's the fastest path.

You don't learn code with your head — you learn it with your hands. 🎉


Appendix A. Frequently Asked Questions (FAQ)

Q. What's the difference between let, const, and var?

  • var is the old keyword — don't use it.
  • let is a variable whose value can change.
  • const can't be changed once it's set. Default to const, and use let only when you need it.

Q. I got a red error in the console. What do I do? Copy the error message as-is and search it on Google or ChatGPT. 99% of the time someone has already run into the same problem. The first line of the message is the most important part.

Q. I want to put the code in a separate file. Create a script.js file and:

<script src="script.js"></script>

Instead of writing directly inside the <script> tag, splitting it into an external file makes things easier to manage once the code gets long.

Q. Isn't JavaScript a security risk? Browsers keep JS inside a sandbox so it can't read files on the user's computer directly. In normal use it is safe. When you use external libraries, though, check where they come from.

Q. I've heard of something called jQuery — what is it? A JavaScript library that was popular in the early 2010s. Modern JavaScript is good enough now that new projects rarely use it. You almost never need to learn it.


Appendix B. Instructor Tips

  • Encourage use of the console from the very first session. If students learn the wrong idea that "running code = refreshing the page", debugging becomes hard later.
  • Don't let them fear error messages. Deliberately make a typo, bring up the error, and demonstrate how to read the message.
  • The DOM concept won't click all at once. Repeat the analogy "HTML converted into objects" several times.
  • The callback function in addEventListener is the hardest concept for beginners. Explain that "you pass a function around like a variable".
  • The final dark mode exercise is the key to satisfaction. Even if you're short on time, make sure everyone follows along with this one. The result is immediate, which is highly motivating.
  • Avoid remarks like "this would be easier with React..." They only confuse beginners.

Written: 2026-05 / License: free to modify and redistribute

Example files

Complete, runnable files used in this lesson. Copy them into your project and experiment.

index.htmlHTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Alex Kim's Interactive Homepage</title>
    <style>
        body {
            font-family: sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            line-height: 1.6;
            background: #ffffff;
            color: #111;
            transition: background 0.3s, color 0.3s;
        }
        h1 { color: #2563eb; }
        .card {
            background: #f3f4f6;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            transition: background 0.3s;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 6px;
            background: #2563eb;
            color: white;
            cursor: pointer;
        }
        button:hover { background: #1d4ed8; }

        /* Dark mode */
        body.dark {
            background: #1a1a1a;
            color: #f3f4f6;
        }
        body.dark .card {
            background: #2a2a2a;
        }
        body.dark h1 {
            color: #93c5fd;
        }
    </style>
</head>
<body>
    <button id="darkBtn">🌙 Dark mode</button>

    <h1>Hi, I'm Alex Kim 👋</h1>
    <p>This is a homepage with interactivity added using JavaScript.</p>

    <div class="card">
        <h2>Click Counter</h2>
        <p>Number of clicks: <span id="count">0</span></p>
        <button id="clickBtn">Click me</button>
    </div>

    <div class="card">
        <h2>Greeting Builder</h2>
        <input id="nameInput" type="text" placeholder="Enter your name">
        <p id="greeting"></p>
    </div>

    <script>
        // 1. Dark mode toggle
        const darkBtn = document.getElementById("darkBtn");
        darkBtn.addEventListener("click", function() {
            document.body.classList.toggle("dark");
            if (document.body.classList.contains("dark")) {
                darkBtn.textContent = "☀️ Light mode";
            } else {
                darkBtn.textContent = "🌙 Dark mode";
            }
        });

        // 2. Click counter
        let count = 0;
        const clickBtn = document.getElementById("clickBtn");
        const display = document.getElementById("count");
        clickBtn.addEventListener("click", function() {
            count = count + 1;
            display.textContent = count;
        });

        // 3. Live greeting builder
        const nameInput = document.getElementById("nameInput");
        const greeting = document.getElementById("greeting");
        nameInput.addEventListener("input", function() {
            const name = nameInput.value;
            if (name.length > 0) {
                greeting.textContent = "Hello, " + name + "!";
            } else {
                greeting.textContent = "";
            }
        });
    </script>
</body>
</html>

Assignment

Assignment 04 — Make the page interactive

Add JavaScript to the page you styled in Assignment 02.

Features

  1. Greeting — a text input and a button. Clicking the button writes Hello, <name>! into a paragraph using textContent.
  2. Counter — a button that increments a number on the page. The count must survive a page refresh (localStorage).
  3. Dark mode — a toggle that switches a dark class on <html>, stores the choice, and respects the saved value on load.
  4. Form validation — an email input; submitting an empty or invalid value shows an error next to the field and does not reload the page.
  5. Console practice — log the current time on load and the count after each increment.

Constraints

  • Put the JavaScript in script.js and load it with defer.
  • Use addEventListener, not inline onclick.
  • Use textContent for user-provided text.
  • No frameworks.

Accessibility

  • The toggle is a <button> with aria-pressed.
  • The error message uses role="alert".
  • Every control is reachable and operable by keyboard.

Done when

  • Refreshing keeps the counter and theme.
  • Submitting an invalid email shows one clear message.
  • The page works with JavaScript errors visible in the console — there are none.
  • The code is committed and deployed.

Learn this lesson with a mentor

Work through the Build Your Homepage series on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now