Variables and Events
beginner25 minLearning 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
document.querySelectorfinds an element on the page using a CSS selector.addEventListener("click", ...)registers a function to run whenever that element is clicked.- Inside the function, we read the input's
.valueand 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.
Log in to track this lesson on your progress dashboard.
Log in