learn.web Back to the curriculum ↗

First steps on the web / 05

JavaScript: the behavior

Make pages respond to people with variables, functions, events, and the DOM.

Time
80 min
Mode
Learn → Make → Check
Path
Web Foundations

By the end, you can…

JavaScript makes pages respond

JavaScript runs in the browser and can read and change the page. The usual recipe: select an element with querySelector, listen for an event with addEventListener, and update the page with textContent or classList.

Treat JavaScript as an enhancement. A page whose links, forms, and content work without scripts is robust, and its interactive layer can only improve on that.

Add one real interaction

Choose a small, genuine interaction: a button that counts, a greeting that changes, a list you can add to, a theme that toggles. Write the HTML for it first, then attach behavior in a separate script.

Test with JavaScript blocked: the content must remain readable and the page must not be broken. Then turn JavaScript back on and confirm the interaction works.

Working example
const button = document.querySelector("button");
const output = document.querySelector("output");
let count = 0;
button.addEventListener("click", () => {
  count += 1;
  output.textContent = count;
});

Your studio task

Make — Add one genuine interaction to your page.

  1. Pick one small interaction and write its HTML first.
  2. Select the elements and attach an event listener.
  3. Update the page and keep the interaction state in the page itself.
  4. Verify the core page works with JavaScript blocked.
Definition of done

A person can change something on the page by clicking or typing, and the core content still works with JavaScript blocked.

Open the interactive lesson with its workspace ↗

Knowledge check

Which method selects the first element matching a CSS selector?
  1. querySelector
  2. querySelectorAll
  3. getElement
Reveal answer (A)

querySelector returns the first matching element; querySelectorAll returns all.

Which event fires when a person clicks an element?
  1. submit
  2. click
  3. load
Reveal answer (B)

click fires on activation; submit is specific to forms.