Maze game
Keyboard controls, three levels, a timer and collision detection.
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.
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.
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.
Visual Studio Code gives you three big advantages when writing JavaScript:
document. or localStorage., VS Code suggests every valid property and explains what parameters it expects.(, [, {, or " automatically inserts the closing partner.Two Pro Debugging Moves:
console.table(projects) — When logging arrays of objects, this prints a beautiful spreadsheet table right inside your browser console!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.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 }]; 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.
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 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.
| Code | What 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 = true | Hides 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.
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
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.
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 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.
Keyboard controls, three levels, a timer and collision detection.
A physics model showing tension and compression in a truss.
Brightness, contrast and grayscale applied to an image on a canvas.
Twenty-five minutes of focus, then a five minute break, with sound off by default.
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.
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.
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.
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.
[{ title, tags }]) organize information identically, enabling instant searching, sorting, and dynamic DOM rendering. Credit: Wikimedia Commons · Public domain · source
projects.filter(...)) execute Otlet's dream of instant global information indexing in browser memory. Credit: Mundaneum / Wikimedia Commons · Public domain · source 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.
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.
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 Add a <button id="theme-btn">🌙 Dark Mode</button> to your navigation bar and implement the theme switcher script above.
Add filter pills (e.g. "All", "Games", "Tools") that filter project cards by category tag when clicked, highlighting the currently active button.
Implement an accessible <dialog> modal that populates dynamically with the clicked project’s title, screenshot, and writeup.
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.