Variables and Events

beginner25 min

Learning objectives

  • Declare variables with let and const
  • Respond to user events such as clicks
  • Update page content using the DOM

Learn

Making pages interactive

HTML gives structure and CSS gives style — JavaScript gives behaviour.

const button = document.querySelector("#greet-btn");
const output = document.querySelector("#output");

button.addEventListener("click", () => {
  const name = document.querySelector("#name-input").value;
  output.textContent = `Hello, ${name}!`;
});

Breaking it down

  1. document.querySelector finds an element on the page using a CSS selector.
  2. addEventListener("click", ...) registers a function to run whenever that element is clicked.
  3. Inside the function, we read the input's .value and update the output element's .textContent.

let vs const

Use const by default — it signals "this variable is never reassigned". Use let only when a variable's value genuinely needs to change later (like a counter). Avoid var — it has confusing scoping rules that modern JavaScript avoids.

Try it yourself

In the HTML/CSS/JS Lab, add a button that changes the background colour of the page each time it's clicked.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab
Log in to track this lesson on your progress dashboard.
Log in