← Back to the Build Your Homepage series
πŸš€
EPISODE 04
From a static page to a "living" page

Bring Your Homepage to Life with JavaScript

Add real behavior to your homepage: respond to clicks, change content with the DOM, fetch data, and store state. Just enough JavaScript to feel the spark.

JavaScriptDOMEventsVariablesFunctions
Duration
⏱ About 4 hours
Level
πŸ“Š Beginner (after Lesson 3)
Prerequisite
🎯 Lessons 1–3 (HTML, CSS, Git)
OUTCOME
A homepage that responds to user interaction (toggles, counters, fetches)

What you'll learn

  • 1Run JavaScript in the browser and read the console
  • 2Declare variables and call functions
  • 3Select and modify HTML elements via the DOM
  • 4Respond to click and input events
  • 5Use fetch to pull data from a public API

1. What is JavaScript?

  • HTML = structure (the bones)
  • CSS = style (the look)
  • JavaScript = behavior (the brain)

JS is the only language that runs natively in every browser. With it, your page can react to users, fetch data, and update itself without a reload.

2. Attaching JavaScript to HTML

html
<!-- inline (avoid for real projects) -->
<button onclick="alert('hi')">Click</button>

<!-- external file (recommended) -->
<script src="main.js" defer></script>
πŸ’‘

Always use defer on script tags. The script runs after HTML is parsed, so document.querySelector won’t return null.

3. Variables, Types, Operators

javascript
let count = 0;          // mutable
const name = "Alice";   // immutable binding
const PI = 3.14;

// Types
const n  = 42;          // number
const s  = "hello";     // string
const b  = true;        // boolean
const a  = [1, 2, 3];   // array
const o  = { x: 1 };    // object

// Operators
count += 1;
const full = name + " Doe";   // "Alice Doe"
const isOk = count > 0 && name;
⚠️

Use const by default, let when you must reassign, never var (legacy).

4. Functions

javascript
// Function declaration
function greet(name) {
  return `Hello, ${name}!`;
}

// Arrow function (compact)
const square = (n) => n * n;

console.log(greet("Alice"));   // Hello, Alice!
console.log(square(5));         // 25

Template literals (backticks) let you embed expressions with ${...} and use multi-line strings.

5. Control Flow

javascript
if (count > 10) {
  console.log("many");
} else if (count > 0) {
  console.log("some");
} else {
  console.log("none");
}

for (let i = 0; i < 5; i++) {
  console.log(i);
}

const nums = [1, 2, 3];
nums.forEach((n) => console.log(n));
const doubled = nums.map((n) => n * 2);   // [2, 4, 6]

6. The DOM β€” Reaching into HTML

The DOM (Document Object Model) is JavaScript's view of the HTML on the page.

javascript
// Select elements
const title    = document.querySelector("h1");
const buttons  = document.querySelectorAll(".btn");

// Read and write
title.textContent = "New heading";
title.style.color = "crimson";
title.classList.add("highlight");

// Create and append
const li = document.createElement("li");
li.textContent = "New task";
document.querySelector("ul").appendChild(li);

7. Events

javascript
const btn = document.querySelector("#counter");
let count = 0;

btn.addEventListener("click", () => {
  count += 1;
  btn.textContent = `Clicked ${count} times`;
});

const input = document.querySelector("#name");
input.addEventListener("input", (e) => {
  document.querySelector("#preview").textContent = e.target.value;
});

Common events

EventFires when
clickThe element is clicked
inputAn <input> value changes
submitA <form> is submitted
keydownA key is pressed
mouseoverMouse enters the element

8. Async β€” fetch & promises

javascript
// Fetch a public API
async function loadUsers() {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const users = await res.json();
  document.querySelector("#count").textContent = users.length;
  users.forEach((u) => {
    const li = document.createElement("li");
    li.textContent = `${u.name} (${u.email})`;
    document.querySelector("#users").appendChild(li);
  });
}

loadUsers().catch(err => console.error(err));
πŸ’‘

Open the browser DevTools (F12) β†’ Console tab to see errors and console.log output.

9. localStorage β€” Persisting State

javascript
// Save a value
localStorage.setItem("theme", "dark");

// Read on next page load
const saved = localStorage.getItem("theme");
if (saved) document.documentElement.dataset.theme = saved;

// Save an object (must JSON.stringify)
localStorage.setItem("todos", JSON.stringify(["a", "b"]));
const todos = JSON.parse(localStorage.getItem("todos") ?? "[]");

10. Wrap-up

  • You can declare variables, write functions, and use control flow
  • You can read and modify the page via the DOM
  • You can respond to user events
  • You can fetch external data and persist state in localStorage

Next lesson, we leave plain HTML and step into React + Next.js β€” the way real apps are built.

πŸ›  Mini Projects

Click counter β€” buttons that increment, decrement, and reset a number on the page
Live theme toggle that flips between light/dark and saves the choice in localStorage
User list β€” fetch from JSONPlaceholder and render each user as an <li>
To-do list β€” add, complete, and delete items; persist to localStorage
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—