Back to the catalogue Courses

JavaScript: make a page interactive

Add reliable interaction to a page: DOM, events, state, fetch and accessibility.

MDJAD Intermediate 16 min read

Objectives and prerequisites

By the end of this course, you will be able to add reliable interaction to an HTML page: read and update the DOM without breaking accessibility, respond to events, organise state, call an API and handle errors. The common thread is a filterable product catalogue, built step by step.

Prerequisites: you can write a structured HTML page and style it with CSS (course F02). No framework knowledge is required. The examples use modern JavaScript in a browser, with ES modules, fetch, async/await and standard DOM APIs.

Path: chapters 1 to 4 cover the language and data; chapters 5 to 7 cover the DOM, events and state; chapters 8 and 9 cover asynchronous code and the network; chapters 10 and 11 organise code, debugging and accessibility; chapter 12 assembles the catalogue. Allow four to six hours of practice.

Convention: each example names the file concerned. The code runs in a recent browser; developer tools are assumed to be available. No secret or token belongs in front-end code, because everything sent to the browser is public.

1. The browser execution model

The browser runs JavaScript on a main thread, in cooperation with page rendering. A long script blocks clicks, scrolling and animations. The browser runs an event loop: it finishes the current task, drains microtasks, then moves to the next task. Understanding this loop explains why a promise does not run "immediately".

A JavaScript file loads with <script>. Without an attribute, the script blocks HTML parsing. defer delays execution until parsing is complete, in file order. type="module" enables ES modules and also delays execution. For a modern page, prefer a module or defer.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Catalogue</title>
</head>
<body>
  <main id="app"></main>
  <script type="module" src="/js/main.js"></script>
</body>
</html>

console.log prints a value in the developer tools console. console.table suits arrays of objects; console.error reports an error. These outputs do not replace the user interface: a message for the visitor must appear in the page.

Strict mode is enabled by default in modules. It turns some silent errors into exceptions, such as assigning to an undeclared variable. In a classic script, add 'use strict'; at the top of the file. Strict mode makes code more predictable.

Finally, distinguish load time from execution time. The HTML may be displayed before the module is ready. The interface must remain readable and usable during that delay; a loading indicator or fallback content avoids a blank page.

2. Values, types and equality

JavaScript has primitive types: string, number, boolean, null, undefined, bigint and symbol. Objects, arrays and functions are objects. typeof returns a string, with two historical traps: typeof null is "object" and typeof [] is "object".

const price = 12.5;
const quantity = 3;
const total = price * quantity;

console.log(typeof price);      // "number"
console.log(Number.isInteger(3)); // true
console.log(Number.isNaN(NaN));   // true
console.log(null === undefined);  // false
console.log(0 === -0);            // true
console.log(Object.is(0, -0));    // false

Use === and !==. The == operator applies implicit conversions: "0" == false is true, which surprises. The only case where == null is sometimes used is the "null or undefined" test, but an explicit comparison is clearer in a course.

NaN is equal to no value, including itself. Test with Number.isNaN(), not with === NaN. Numbers are binary floats: 0.1 + 0.2 does not give exactly 0.3. For money, work in integer cents or with a decimal library.

Strings are immutable: a method returns a new string. Objects are compared by reference: two objects with the same content are not ===. This distinction explains why modifying an object passed to a function can change the caller's object.

Finally, null means "deliberate absence" and undefined means "value not provided". Do not use them interchangeably. A function that returns nothing produces undefined; a missing property is undefined. Document your function contracts.

3. Functions, scope and closures

A function groups reusable processing. A declaration is hoisted; an expression assigned to a constant is not. Arrow functions have a short syntax and do not have their own this, which is useful for callbacks. For an object method, prefer method syntax.

function formatPrice(cents) {
  return new Intl.NumberFormat('en-IE', {
    style: 'currency',
    currency: 'EUR',
  }).format(cents / 100);
}

const applyDiscount = (cents, percent) => {
  return cents - Math.round((cents * percent) / 100);
};

console.log(formatPrice(applyDiscount(1750, 10))); // €15.75

Scope determines where a variable is visible. const and let are limited to the block; var is function-scoped and should be avoided. A variable declared inside a function is not visible outside. A global variable is accessible everywhere, which creates hidden dependencies.

A closure is a function that keeps access to the variables of its creation environment, even after that environment ends. It can create a private counter or a configured function. Each call to the factory creates an independent state.

function createCounter(start = 0) {
  let value = start;
  return {
    increment() {
      value += 1;
      return value;
    },
    current() {
      return value;
    },
  };
}

const counter = createCounter(2);
counter.increment();
console.log(counter.current()); // 3

Default parameters apply when the argument is undefined. The rest parameter ...args collects extra arguments. Named arguments do not exist in JavaScript; a configuration object is often clearer than a long parameter list.

this depends on how a function is called, not where it is defined. A method called on an object receives that object; a detached function loses the link. An arrow function captures the this of its environment and cannot be used as a constructor. For a callback, prefer an arrow function or bind the function explicitly with bind.

Finally, prefer pure functions: same inputs, same output, no side effects. They are easier to test. Isolate side effects — DOM reads, network requests, storage writes — in dedicated functions. This separation makes the catalogue predictable.

4. Arrays, objects and transformations

An array is an ordered list. map transforms each element and returns a new array; filter keeps those that pass a test; find returns the first matching element or undefined; reduce aggregates a value. These methods do not modify the original array.

const products = [
  { name: 'Notebook', price: 350, category: 'stationery' },
  { name: 'Pen', price: 120, category: 'stationery' },
  { name: 'Lamp', price: 2400, category: 'office' },
];

const stationery = products
  .filter((product) => product.category === 'stationery')
  .map((product) => product.name);

const total = products.reduce((sum, product) => sum + product.price, 0);
console.log(stationery); // ["Notebook", "Pen"]
console.log(total);      // 2870

sort mutates the array in place and compares as strings by default; use a comparison function and copy first with [...products], or toSorted where supported. reverse also mutates in place. Mutating methods are a frequent source of bugs.

An object groups named properties. Destructuring extracts values; the rest ...rest copies the properties not extracted. Spread {...product} makes a shallow copy: nested objects remain shared. For a deep copy, use structuredClone when the data is cloneable.

const { name, price, ...details } = products[0];
const updated = { ...products[0], price: 400 };
const label = products[2]?.name ?? 'Unknown';

console.log(name, price, details);
console.log(updated.price);
console.log(label);

Optional chaining ?. avoids an error when an intermediate value is absent. The ?? operator provides a default only for null or undefined, unlike ||, which also replaces 0 and "". Choose deliberately.

Finally, Map and Set are useful for non-string keys or unique values. For a small catalogue, an array is enough. Do not introduce a complex structure without a measured need: readability remains the priority.

5. The DOM: read and update safely

The DOM is the tree of page elements. document.querySelector returns the first element matching a CSS selector, or null. querySelectorAll returns a static list. Always check that an element exists before using it, especially when the HTML may change.

const list = document.querySelector('[data-product-list]');
const template = document.querySelector('#product-template');

if (!list || !template) {
  throw new Error('The catalogue is incomplete.');
}

function renderProduct(product) {
  const node = template.content.cloneNode(true);
  node.querySelector('[data-name]').textContent = product.name;
  node.querySelector('[data-price]').textContent = formatPrice(product.price);
  return node;
}

textContent inserts plain text and escapes special characters. innerHTML interprets HTML: never use it with data supplied by a user or an untrusted API, or you risk script injection (XSS). If you must build HTML, use elements and attributes created through the DOM.

To change an element, use classList.add, classList.toggle, setAttribute and dataset. Avoid inline styles when a CSS class suffices: presentation stays in CSS, behaviour in JavaScript. HTML must remain semantic.

Replacing a list needs thought. Clearing and recreating every node on each keystroke destroys focus and selections. For a small catalogue, a full render after each change is acceptable; for a long list, update only the affected rows. Measure before optimising.

Finally, plan for empty and error states. An empty list must show a useful message, not blank space. A failed load must offer an action or explain the situation. The interface must remain understandable without JavaScript for essential content.

6. Events and delegation

An event represents an action: click, input, submit, key press. addEventListener associates a function with an element. The event object contains target (the originating element), currentTarget (the listening element) and methods such as preventDefault.

const form = document.querySelector('[data-search-form]');

form?.addEventListener('submit', (event) => {
  event.preventDefault();
  const query = new FormData(form).get('q');
  console.log(String(query).trim());
});

preventDefault stops the native behaviour, such as a form reload. Call it only if you actually handle the action. For a link, preventing navigation without an alternative breaks right-click and opening in a new tab.

Events bubble from the target element to its ancestors: this is propagation. Delegation means listening on a container and identifying the target with event.target.closest(). It works for elements added later and reduces the number of listeners.

list.addEventListener('click', (event) => {
  const button = event.target.closest('[data-add]');
  if (!button) return;
  const id = button.dataset.add;
  addToCart(id);
});

Use click for a button and submit for a form. Also handle the keyboard when the interaction does not use a native control: Enter and Space on a clickable element. The browser already provides keyboard support for <button>, <a> and fields; prefer them over clickable <div> elements.

Finally, remove listeners when a component is destroyed, or use an AbortController with signal. On a single page the risk is low; in an application that recreates views, forgotten listeners accumulate and cause double actions.

7. State, rendering and forms

State is the set of data that determines the display: products, search, category, cart. A single source of truth avoids inconsistencies. The DOM must not be the database: reading a value from displayed text to reuse it is fragile.

const state = {
  products: [],
  query: '',
  category: 'all',
  cart: [],
};

function visibleProducts() {
  const query = state.query.trim().toLowerCase();
  return state.products.filter((product) => {
    const matchesQuery = product.name.toLowerCase().includes(query);
    const matchesCategory = state.category === 'all'
      || product.category === state.category;
    return matchesQuery && matchesCategory;
  });
}

function render() {
  const products = visibleProducts();
  list.replaceChildren(...products.map(renderProduct));
  status.textContent = products.length === 0
    ? 'No product matches your search.'
    : `${products.length} product(s) displayed.`;
}

The flow is simple: an action changes state, then calls render(). Rendering reads state and produces the DOM. No other code should modify the same elements, or two sources of truth diverge. This discipline is enough for a small catalogue.

Form fields are controlled by state when the display depends on their value. For a search, listen to input and update state.query. Avoid writing into the field on every render: that moves the caret. If you must, restore the caret position.

Derived data — filtered list, cart total, item count — is computed from state, without being stored twice. A separately stored total can become wrong after a removal. Compute it during rendering or in a dedicated function.

Finally, announce important changes to assistive technologies. An aria-live="polite" region for the result count lets a screen reader follow the filter. Do not flood the user with announcements: reserve them for useful changes.

8. Asynchronous code: promises and async/await

A promise represents a future result: pending, fulfilled or rejected. then registers processing, catch handles failure, finally runs in all cases. async/await is a more readable syntax for consuming promises, not a different mechanism.

async function loadProducts() {
  try {
    const response = await fetch('/api/products.json');
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Loading failed', error);
    return [];
  }
}

await suspends the async function, not the browser. The main thread remains available for other events. An async function always returns a promise; a thrown exception becomes a rejection. try/catch around await therefore catches network and conversion errors.

Two independent calls can run in parallel with Promise.all, then be awaited together. Promise.allSettled waits for all results even if some fail. Promise.race takes the first result, useful for a maximum delay. Choose according to the business need.

Microtasks — promise continuations — run before the next tasks such as timers. This is why a console.log after an await may run after other code. Do not rely on apparent order without understanding it; structure the flow with explicit await.

Finally, do not block the interface with a waiting loop. A loading indicator, a disabled button and an error message make the wait understandable. An operation that may take time must have a maximum delay and a way to cancel.

9. Fetch, network errors and cancellation

fetch returns a promise for a response as soon as headers are received. An HTTP 404 or 500 response is not a rejection: response.ok is false. You must check the status before reading the body. A DNS failure or network cut, however, rejects the promise.

async function fetchJson(url, { timeout = 5000 } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeout);

  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}

AbortController cancels a request. controller.abort() causes an AbortError rejection. Also cancel a request when the user changes the filter quickly: the old response must not overwrite the new one. Keep the latest request identifier or abort the previous one.

Content-Type and Accept headers describe the expected format. For a JSON POST, send Content-Type: application/json and JSON.stringify. Never put a secret key in the front end: it would be visible. Authentication uses a secure cookie or a limited-scope token managed on the server.

Errors must be distinguished: network problem, HTTP status, invalid JSON, unexpected data. A generic "error" message does not help. Log technical details in the console and show an understandable message in the interface. Do not show internal traces to the visitor.

Finally, plan an offline mode or fallback content. If the catalogue cannot load, show products already present in the HTML or an explicit message. A page that stays blank without explanation is a bad experience, even if the code is correct.

10. Modules, organisation and tooling

An ES module exports values with export and imports them with import. Each module has its own scope; variables do not pollute the global object. Imports are hoisted and static, which lets tools build the dependency graph.

// js/format.js
export function formatPrice(cents) {
  return new Intl.NumberFormat('en-IE', {
    style: 'currency',
    currency: 'EUR',
  }).format(cents / 100);
}
// js/main.js
import { formatPrice } from './format.js';

Organise by responsibility: api.js for requests, format.js for display, catalog.js for state and rendering. A main.js file assembles everything. Avoid catch-all modules and circular dependencies, which make initialisation order hard to predict.

Relative paths must include the .js extension in the browser. A bundler may omit it, but the native browser does not. If you use a build tool, document the command and expected output; do not assume the browser understands TypeScript or JSX.

Linting finds unused variables, suspicious comparisons and style errors. A formatter makes code uniform. The two are complementary. Configure them in the project and run them before delivery, like tests.

Finally, version source files and the dependency lock file. Do not version generated files if the build can recreate them. Document commands in the README so a new developer can start without guessing.

11. Debugging, tests and accessibility

Browser developer tools show the console, network, elements and sources. A breakpoint in the Sources tab suspends execution and lets you inspect variables. debugger; in code has the same effect when tools are open. Remove it before production.

To diagnose a problem, reproduce it with a minimal dataset, check state before and after the action, then isolate the faulty function. console.log remains useful, but console.table and breakpoints provide more information. Read the error message and stack trace instead of guessing.

import test from 'node:test';
import assert from 'node:assert/strict';
// filterProducts comes from catalog.js; products is a test fixture.
import { filterProducts } from './catalog.js';

test('filters by category', () => {
  const result = filterProducts(products, { category: 'office' });
  assert.equal(result.length, 1);
  assert.equal(result[0].name, 'Lamp');
});

Pure functions — filtering, formatting, total calculation — can be tested without a browser with Node.js and node:test. DOM interactions are tested with an automated browser or integration tests. Start with pure functions: they cover the richest logic.

Accessibility is part of behaviour. A button must be a <button>, a field must have a <label>, focus must remain visible, and dynamic messages must be announced. Test with the keyboard: tab, enter, space, escape. Test at 200% zoom and with a screen reader if possible.

Finally, JavaScript must enhance a page that already works. The main content, links and search form can exist in HTML; the script adds instant filtering. If the script fails, the user must still be able to browse the catalogue and submit the form.

12. Synthesis: assembling the catalogue

The catalogue combines the building blocks: state, rendering, events, asynchronous loading and accessible messages. HTML provides structure and the form; the module loads data, binds listeners and renders the filtered list. Each part stays small and testable.

const state = { products: [], query: '', category: 'all' };

async function init() {
  state.products = await fetchJson('/api/products.json');
  render();
}

document.querySelector('[data-search]')?.addEventListener('input', (event) => {
  state.query = event.target.value;
  render();
});

document.querySelector('[data-category]')?.addEventListener('change', (event) => {
  state.category = event.target.value;
  render();
});

init().catch((error) => {
  console.error(error);
  const status = document.querySelector('[data-status]');
  if (status) status.textContent = 'The catalogue is unavailable.';
});

Rendering must handle three states: loading, results and error. A loading state shows text or a skeleton; an empty state explains the filter; an error offers a retry. These states are data like any other and must be planned from the start, not added afterwards.

Search should be tolerant: ignore case, extra spaces and, if the business need justifies it, accents. toLowerCase is enough for an exercise; Unicode normalisation with normalize('NFD') can ignore accents. Document the chosen rule.

The cart adds a second dimension: an "add" action updates a quantity, then rendering displays the total. Avoid storing the total separately. If the cart must survive a reload, use localStorage with a schema version and validation of the data read.

Finally, review the user journey: what is visible while loading? What happens if the API fails? Does focus remain logical after a filter? Is the result message announced? A successful catalogue is not only filtered: it remains understandable, accessible and repairable.

Exercise 1 — Types and equality

Predict and then verify the result of "0" == false, "0" === false, NaN === NaN and null == undefined. Explain each result and state the comparison to use in production code.

Solution

"0" == false is true because of implicit conversion; "0" === false is false because the types differ; NaN === NaN is false, so use Number.isNaN; null == undefined is true. In production, use === and !==, and Number.isNaN for numbers.

Exercise 2 — Closure and counter

Write a factory createCounter(start) that returns increment() and current(). Two counters created separately must have independent states. Test a counter starting at 0.

Solution

The factory declares let value = start and returns two methods that close over that variable. Each call creates a new scope, hence independent state. increment() increases and returns the value; current() reads without modifying. The test verifies that one does not affect the other.

Exercise 3 — Array transformations

From an array of products, produce the names in the "office" category, sorted by ascending price, then compute the total of all products. Use filter, map, toSorted or a copy, and reduce.

Solution

products.filter(p => p.category === 'office').toSorted((a, b) => a.price - b.price).map(p => p.name) produces the sorted names. The total is products.reduce((sum, p) => sum + p.price, 0). No method modifies the original array when toSorted is used; with sort, copy first.

Exercise 4 — Safe DOM rendering

Write a function that creates a product row with a name and a price. The name comes from an API and may contain <script>. Use textContent and explain why innerHTML would be dangerous.

Solution

The function creates an <li>, one element for the name and one for the price, then assigns textContent. Special characters are displayed as text. innerHTML would interpret the tag and could execute script or break the structure: that is XSS injection.

Exercise 5 — Delegation and form

Bind a single listener on the list to handle "add to cart" buttons, including rows added after loading. Also handle search form submission with preventDefault.

Solution

The listener is placed on the container; event.target.closest('[data-add]') identifies the button, then dataset.add provides the identifier. For the form, listen to submit, call preventDefault and read FormData. Delegation covers future elements and avoids multiplying listeners.

Exercise 6 — Robust fetch

Write a loadJson(url) function that checks response.ok, converts JSON, handles errors and displays a message in a [data-status] element. Provide cancellation with AbortController.

Solution

The function creates a controller, calls fetch with signal, checks response.ok, reads response.json() and catches errors in try/catch. The status shows "loading", then the result count or an error message. controller.abort() cancels a request that is no longer needed.

Capstone — accessible filterable catalogue

Deliver a catalogue page with a search form, a category filter, a product list loaded as JSON and a simple cart. Filtering is instant, the total is computed, empty, loading and error states are displayed, and important messages are announced with aria-live. Keyboard use and 200% zoom must be verified.

Grading: semantic HTML structure; no innerHTML with untrusted data; single state and deterministic rendering; delegated events; fetch with status, errors and cancellation; tested pure functions; accessible messages; no secret key in the front end.

Common mistakes and debugging method

Classic mistakes: comparing with ==, forgetting that NaN is never equal to itself, mutating a shared array, using innerHTML with user input, storing the total twice, forgetting preventDefault, ignoring response.ok, letting an old request overwrite a recent one, and recreating the DOM on every keystroke without managing focus.

Method: reproduce with little data, check state and DOM, read the console and Network tab, isolate the function, then add a test. If behaviour depends on event order, simplify the flow. If the interface flickers, look for an unnecessary full render. If a click does not respond, check delegation and the presence of the element.

Self-assessment

You must be able to explain the event loop, choose ===, write a closure, transform an array without mutating it, create and update the DOM safely, delegate an event, organise state, consume a promise, check an HTTP status, cancel a request and test a pure function.

Self-assessment: I can build the catalogue without a framework; I can justify each listener; I can display an empty state; I can explain why textContent protects against injection; I can name the three states of a load. To go further, study Web Components, integration tests and storage APIs.

References