Build Your Own Web

Build this website with blocks

Try another way to build: snap together HTML, CSS and behavior blocks, change their fields, and watch your website update. Start with this lesson’s project or try a code example below.

Want to keep what you build? Web Studio holds a drawing, blocks and code in one project that you can share on the class site and publish as your own website.

Lesson 4 of the pathway · 60–75 minutes · You need the styled page from Lesson 3

Make It Respond with JavaScript

HTML is the structure and CSS is the design. JavaScript is the part that reacts: it reads what a visitor did, decides something, and changes the page. By the end of this lesson your own site will have a search box that filters your project cards as you type.

Work in script.js. Confirm the last line before </body> in index.html is <script src="script.js"></script>. The position matters: code runs the moment it loads, and it cannot find elements the browser has not built yet.

First tool: see what your program believes

Programs almost never fail mysteriously. They do exactly what you wrote, on values you did not expect. console.log() is how you inspect what the program is doing step by step.

const name = "Ada";
console.log("name is:", name);
console.log("length is:", name.length);

// Pro Tip 1: Wrap in braces to print the variable name automatically!
console.log({ name }); // prints: { name: "Ada" }

Open your browser, press F12 (or right-click and choose Inspect), then click the Console tab. Red text there is an error with a file name and a line number — click it to jump straight to the source line in your code.

Writing JavaScript in VS Code

Visual Studio Code gives you three big advantages when writing JavaScript:

Two Pro Debugging Moves:

  1. console.table(projects) — When logging arrays of objects, this prints a beautiful spreadsheet table right inside your browser console!
  2. debugger; — Type this keyword on any line in script.js. When your browser encounters it with DevTools open, it pauses program execution so you can hover over any variable and inspect its live value.

Values and the boxes that hold them

A variable is a name for a value. Use const unless you know the value must change; then use let. Do not use var.

const siteName = "Maya's Creation Station"; // string: text in quotes
let visitCount = 0;                          // number: no quotes
const isPublished = true;                    // boolean: true or false

visitCount = visitCount + 1;   // fine, visitCount is let
// siteName = "something else"; // error: siteName is const

const is not a restriction. It is a promise to your future self that this name will always mean this thing, and that promise is what makes code readable a month later.

Two kinds of collection hold the rest of your data:

// An array: an ordered list. Positions start at 0.
const tags = ["game", "physics", "art"];
console.log(tags[0]);      // "game"
console.log(tags.length);  // 3

// An object: named fields describing one thing.
const project = {
  title: "Maze game",
  tags: ["game", "keyboard"],
  finished: true
};
console.log(project.title);   // "Maze game"

// An array of objects: the normal shape of real site data.
const projects = [project, { title: "Study timer", tags: ["tool"], finished: false }];

Functions: a name for a job

A function packages steps so you can run them whenever you like, without repeating them.

function describe(project) {          // project is the input, called a parameter
  return project.title + " — " + project.tags.join(", ");
}

console.log(describe(project));      // "Maze game — game, keyboard"

return hands a value back to whoever called the function. A function without one still does its work, but answers undefined — so a logged undefined usually means a missing return.

Ada Lovelace's 1843 diagram of an algorithm for Charles Babbage's Analytical Engine to calculate Bernoulli numbers
Ada Lovelace's First Computer Algorithm (1843) The world's first published computer program. In her notes on Charles Babbage's Analytical Engine, Ada Lovelace created this table detailing variable memory registers, arithmetic operations, loop cycles, and conditional branching to compute Bernoulli numbers. Every JavaScript function, loop, and variable assignment builds directly upon Lovelace's foundational insights. Credit: Ada Lovelace / Science Museum London / Wikimedia Commons · Public domain · source
Charles Babbage's Difference Engine No. 2 at the London Science Museum showing bronze calculation gear columns
Babbage's Mechanical State Registers (Difference Engine No. 2) Charles Babbage designed columns of rotating toothed brass gears to store numeric variables and execute automated arithmetic operations mechanically. In JavaScript, memory variables (let count = 0) and functions represent the digital successor to these mechanical state registers, storing and transforming values deterministically. Credit: London Science Museum / Wikimedia Commons · CC BY-SA 2.0 · source

The DOM: your page, as objects

When the browser loads your HTML, it parses the markup into a live hierarchy of in-memory C++ objects called the Document Object Model (DOM). The DOM exists because re-parsing raw HTML text on every user click would be prohibitively slow and computationally expensive. By keeping a live object graph in memory, JavaScript can query and update nodes directly (such as modifying el.textContent or setting el.hidden = true). This means the browser's rendering engine only repaints the specific altered nodes rather than reloading the page, which produces instant visual feedback.

The four DOM moves worth memorising
CodeWhat it does
document.querySelector(".card")Finds the first element matching a CSS selector, or null
document.querySelectorAll(".card")Finds every match, as a list you can loop over
el.textContent = "Hi"Replaces the text inside an element
el.hidden = trueHides the element from sight and from screen readers

You will also use el.classList.add("is-active"), .remove() and .toggle(). These let JavaScript decide which state an element is in while CSS decides what that state looks like — a better split than writing colors in your JavaScript.

If querySelector returns null the selector matched nothing, and the next line fails with "Cannot read properties of null". Check the spelling, the dot before a class name, and that your script runs after the HTML.

Ernst Haeckel's 1874 Pedigree of Man diagram illustrating genealogical relationships as a branching tree
Ernst Haeckel's Tree of Life (1874) and the DOM Tree Haeckel's iconic genealogical tree illustrates how a central root branches upward into main trunks, boughs, and individual leaves. The browser constructs the Document Object Model (DOM) identically: the root document node branches into <html>, which divides into <head> and <body> branches, ending in individual element nodes that JavaScript navigates using parent-child traversal. Credit: Ernst Haeckel / Wikimedia Commons · Public domain · source
Charles Darwin's 1837 sketch from his notebook showing evolutionary branching with the words I think at the top
Charles Darwin's Node Branching Diagram (1837) Darwin's famous 1837 “I think” sketch demonstrates how parent nodes fork into descendant branches. In the browser DOM, this hierarchy governs how styles cascade down from ancestors to children and how user events (like clicks) bubble upward from target elements to root listeners. Credit: Charles Darwin / Cambridge University Library / Wikimedia Commons · Public domain · source

Events: waiting for the visitor

Your code should not run in one straight line and stop; it should wait. Because the browser runs JavaScript on a single thread alongside layout and rendering, executing code in a blocking loop would freeze the interface and prevent user interactions. Therefore, browsers use an event-driven architecture: addEventListener registers a callback function in the browser's event table. When a user clicks or types, the browser places that event into an event queue. This means your function executes only when the event loop reaches it, keeping the page completely responsive to touch, scroll, and keystrokes while waiting.

const button = document.querySelector("#say-hi");

button.addEventListener("click", function () {
  console.log("The button was clicked");
});

Three event names cover most work: "click" for buttons, "input" for text fields (it fires on every keystroke, including paste), and "submit" for forms. You never call that function yourself — you hand it to the browser, which calls it.

Portrait of Brendan Eich, creator of the JavaScript programming language
Brendan Eich (Creator of JavaScript) In May 1995, Brendan Eich developed the initial version of JavaScript (originally codenamed Mocha, then LiveScript) in just ten days at Netscape Communications. Designed to run directly inside web browsers alongside HTML, JavaScript transformed the web from static document viewing into an interactive, event-driven computing platform. Credit: Mozilla Foundation / Wikimedia Commons · CC BY-SA 3.0 · source
Screenshot of Netscape Navigator 2 browser, the first browser with JavaScript support
Netscape Navigator 2.0 (The First JavaScript Browser, 1996) Netscape Navigator 2.0 was the first web browser to ship with JavaScript and the Document Object Model (DOM Level 0). It enabled client-side form validation, dynamic page changes, and event listeners responding to user clicks and keystrokes without round-tripping to a remote server. Credit: Indolering / Wikimedia Commons · CC0 1.0 Public Domain · source
Row of telephone switchboard operators with headsets plugging patch cords into exchange jacks in 1910
Telephone Switchboard Exchange: The Human Event Loop (1910) Switchboard operators sat before banks of annunciator lamps and jack sockets. When a customer lifted their receiver, an indicator light flashed (event trigger); the operator plugged in a patch cord (listener callback) and connected the circuit. The browser's single-threaded event loop processes clicks, keystrokes, and timers using the exact same dispatch-and-callback model. Credit: Library of Congress / Wikimedia Commons · Public domain · source
Antique brass Morse telegraph transmission key and receiving sounder instrument
Morse Telegraph Key: Event Listeners in Action When an operator presses a telegraph spring key down, electrical contacts close, sending an electrical impulse across the wire that trips the distant receiver's electromagnetic armature. In JavaScript, button.addEventListener("click", handler) implements the exact digital equivalent: waiting dormant until an external physical contact dispatches an impulse. Credit: Musée des Arts et Métiers / Wikimedia Commons · Public domain · source

The project: search that filters cards

Here is the finished behaviour. Type in the box; cards that do not match disappear and the count updates. Try maze, then Maze, then a word that matches nothing.

Lab: filter a list of projects

Maze game

Keyboard controls, three levels, a timer and collision detection.

Bridge simulator

A physics model showing tension and compression in a truss.

Photo filters

Brightness, contrast and grayscale applied to an image on a canvas.

Study timer

Twenty-five minutes of focus, then a five minute break, with sound off by default.

Weather log

A week of temperature readings charted from data I collected myself.

What the code is deciding, step by step:

 

That trace is not magic. It is exactly what console.log() would print for each card on each keystroke — the same information, shown on the page so you can watch it while you type.

Check. Typing maze should leave one card and report "1 of 5 projects shown". Typing MAZE must give the identical result. Typing zz should hide everything and say so. Clearing the box brings all five back and returns your cursor to the field.

Repair. If your own version hides every card as soon as you type one letter, log your search term: you are almost certainly comparing lowercase page text against a capital letter, or comparing against text that still has spaces around it. If nothing at all happens, log the result of querySelectorAll — a length of 0 means your selector and your HTML disagree.

Build it yourself, one stage at a time

Type each stage into script.js, save, and refresh before writing the next one. Watching one stage work is worth more than pasting all six.

Stage 1 — get the elements. Nothing can happen until the code holds the things it will change.

const searchBox = document.querySelector("#search");
const cards     = document.querySelectorAll(".card");
const countLine = document.querySelector("#count");

console.log("cards found:", cards.length);   // expect your real number, not 0

Stage 2 — read the value, and clean it.

function filterCards() {
  const term = searchBox.value.trim().toLowerCase();
  console.log("term:", term);
}

.trim() removes whitespace from both ends, which means an accidental space added by a mobile virtual keyboard will not prevent "maze " from matching "maze". .toLowerCase() converts every character to lowercase. This is essential because JavaScript string comparison is strictly case-sensitive: "Maze" === "maze" evaluates to false. Therefore, converting both the search term and the card text to lowercase normalizes them to a single canonical format, which ensures searches work reliably regardless of capitalization.

Stage 3 — loop over every card.

  cards.forEach(function (card) {
    const text = card.textContent.toLowerCase();
  });

Stage 4 — decide. includes() answers true or false: does this text contain that text anywhere?

    const matches = text.includes(term);

Stage 5 — show or hide. Use hidden, not a CSS class that only fades the card. A card hidden with hidden is also removed from what a screen reader announces, which is what you want.

    card.hidden = !matches;   // ! means "not"

Stage 6 — report the count, and listen. Here is the whole file:

/* script.js — filter the project cards as the visitor types. */

const searchBox = document.querySelector("#search");
const cards     = document.querySelectorAll(".card");
const countLine = document.querySelector("#count");

function filterCards() {
  // 1. Read what was typed and normalise it for comparing.
  const term = searchBox.value.trim().toLowerCase();
  let visible = 0;

  // 2. Ask each card whether it matches, then show or hide it.
  cards.forEach(function (card) {
    const matches = card.textContent.toLowerCase().includes(term);
    card.hidden = !matches;
    if (matches) {
      visible = visible + 1;
    }
  });

  // 3. Tell the visitor what happened. Never leave them guessing.
  if (visible === 0) {
    countLine.textContent =
      'No projects match "' + searchBox.value + '". Try a shorter word, or clear the box to see all ' + cards.length + '.';
  } else {
    countLine.textContent = visible + " of " + cards.length + " projects shown.";
  }
}

// 4. Run it on every keystroke, and once at startup.
searchBox.addEventListener("input", filterCards);
filterCards();

The matching HTML needs three things: <input type="search" id="search"> with a real <label for="search">, a <p id="count"> carrying aria-live="polite", and cards with class="card". That aria-live is what makes a screen reader announce the new count.

Notice the last line: calling filterCards() once at startup makes the count correct before anyone types. A page that starts blank looks broken.

Empty results are a design decision

The most common failure in a student search box is not a crash. It is a page that goes blank and says nothing, leaving the visitor unable to tell whether they searched badly or your site broke.

An empty state owes the visitor three things: what happened, why, and what to do next. "No results" gives one of the three. The message in Stage 6 gives all three — it names the term, and it offers a way back.

Add a visible way out as well, so nobody has to select and delete text to recover:

const clearButton = document.querySelector("#clear");

clearButton.addEventListener("click", function () {
  searchBox.value = "";
  filterCards();      // re-run so the cards come back
  searchBox.focus();  // put the cursor back where they were working
});

That focus() line is small and it matters. Without it, a keyboard user who clicks Clear is dropped at the button with no obvious place to continue.

Building the list from data

Once the search works, notice that your card HTML repeats itself. You can keep the data in one array and let JavaScript write the cards, so adding a project is one line instead of eight.

const projects = [
  { title: "Maze game",    blurb: "Keyboard controls and three levels." },
  { title: "Study timer",  blurb: "Twenty-five minutes, then a break." }
];

const list = document.querySelector("#project-list");

list.innerHTML = projects.map(function (project) {
  return "<li class='card'><h3>" + project.title + "</h3><p>" + project.blurb + "</p></li>";
}).join("");

map turns each object into a string of HTML and join("") glues them together. Build the list before calling querySelectorAll(".card"), or the search finds nothing — those cards do not exist yet.

Be honest about the limit. This data lives inside your own file. Writing innerHTML from text a stranger typed is how real sites get attacked, so only ever build HTML from data you wrote yourself. Anything typed by a visitor goes into textContent, never innerHTML.

Oak wooden library card catalog cabinet showing multiple labeled drawers with brass pull handles
The Library Card Catalog: Structured Array Data Before computer memory existed, libraries maintained structured datasets on standardized 3×5 index cards categorized by author, subject, and call number. In JavaScript, arrays of objects ([{ title, tags }]) organize information identically, enabling instant searching, sorting, and dynamic DOM rendering. Credit: Wikimedia Commons · Public domain · source
Paul Otlet at the Mundaneum surrounded by floor-to-ceiling rows of card catalog drawers in Brussels
Paul Otlet at the Mundaneum (The Physical Search Engine, 1910) Belgian visionary Paul Otlet assembled over 12 million index cards in Brussels with cross-referenced classifications, answering public queries submitted via mail and telegraph. JavaScript filtering algorithms (projects.filter(...)) execute Otlet's dream of instant global information indexing in browser memory. Credit: Mundaneum / Wikimedia Commons · Public domain · source

Remembering one preference

localStorage stores small pieces of text in the visitor's own browser and gives them back on the next visit. Use it for one small preference, such as a compact view.

const toggle = document.querySelector("#compact");

// Read the saved answer when the page loads. It is always text.
if (localStorage.getItem("compact") === "yes") {
  toggle.checked = true;
  document.body.classList.add("is-compact");
}

toggle.addEventListener("change", function () {
  document.body.classList.toggle("is-compact", toggle.checked);
  localStorage.setItem("compact", toggle.checked ? "yes" : "no");
});

Say clearly what this does and does not do. It saves in this browser on this device only. It is not an account, it does not reach a server, and the same person on their phone starts fresh. A visitor can clear it at any time, and some private-browsing modes refuse to store anything — so your page must still work when nothing comes back. Never store anything personal in it.

Essential interaction: Dark / Light Mode Switcher

Remember the CSS tokens from Lesson 3? Now you can let visitors switch themes with a single button, and remember their choice between visits:

// 1. Find the toggle button in the header
const themeBtn = document.querySelector("#theme-btn");

// 2. Check if dark mode was previously saved
if (localStorage.getItem("theme") === "dark") {
  document.body.classList.add("dark-theme");
  if (themeBtn) themeBtn.textContent = "☀️ Light Mode";
}

// 3. Listen for clicks and toggle the class
if (themeBtn) {
  themeBtn.addEventListener("click", function () {
    document.body.classList.toggle("dark-theme");
    const isDark = document.body.classList.contains("dark-theme");

    // Update button text and persist in localStorage
    themeBtn.textContent = isDark ? "☀️ Light Mode" : "🌙 Dark Mode";
    localStorage.setItem("theme", isDark ? "dark" : "light");
  });
}

Because CSS variables control the colors, this single JavaScript snippet updates every element on the entire site instantaneously.

Essential interaction: Project Detail Modal Dialog

When a visitor clicks on one of your project cards, popping up a modal window with extra screenshots and design details makes your site feel like a professional portfolio. Modern browsers support the native HTML5 <dialog> element:

<!-- In your index.html -->
<dialog id="project-modal">
  <h3 id="modal-title">Project Details</h3>
  <p id="modal-desc">Detailed overview and playtest notes.</p>
  <button type="button" id="modal-close">Close</button>
</dialog>
// In your script.js
const modal = document.querySelector("#project-modal");
const closeBtn = document.querySelector("#modal-close");

// Open modal when any card button is clicked
document.querySelectorAll(".card button").forEach(function (button) {
  button.addEventListener("click", function () {
    modal.showModal(); // Built-in: disables background and traps focus!
  });
});

// Close modal when close button is clicked
closeBtn.addEventListener("click", function () {
  modal.close();
});

// The browser automatically closes  when the visitor presses Escape!

Level-Up Challenges for JavaScript

Tier 1: Theme Switcher

Add a <button id="theme-btn">🌙 Dark Mode</button> to your navigation bar and implement the theme switcher script above.

Tier 2: Category Filter Buttons

Add filter pills (e.g. "All", "Games", "Tools") that filter project cards by category tag when clicked, highlighting the currently active button.

Tier 3: Project Detail Modal

Implement an accessible <dialog> modal that populates dynamically with the clicked project’s title, screenshot, and writeup.

Before you move on

Test your search with the mouse, then with the keyboard alone: Tab to the field, type, Tab to Clear, press Enter. Screenshot a successful search and your empty state, and keep both as evidence. Next lesson you will break a feature like this one and repair it.