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.
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
<!-- 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
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
// 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)); // 25Template literals (backticks) let you embed expressions with ${...} and use multi-line strings.
5. Control Flow
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.
// 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
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
| Event | Fires when |
|---|---|
| click | The element is clicked |
| input | An <input> value changes |
| submit | A <form> is submitted |
| keydown | A key is pressed |
| mouseover | Mouse enters the element |
8. Async β fetch & promises
// 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
// 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
All lecture materials and example code are openly available on GitHub.
View on GitHub β