Reacting to Clicks
So far, your scripts have done everything at once, when the page loaded. But a page becomes interactive when it reacts to what the user does. Things that happen on a page, such as a click, a key press or typing into a field, are called events.
A button is the button element, for example <button id="hello">Say hello</button>. To make it do something, tell it which function to run when it's clicked:
const helloButton = document.querySelector("#hello");
const message = document.querySelector("#message");
helloButton.addEventListener("click", function () {
message.textContent = "Hello!";
});The method addEventListener() takes two arguments: the name of the event in quotes ("click") and a function. The function has no name here; it's written right where it's needed. Notice how the code ends: } closes the function, ) closes the parentheses of addEventListener(, and then comes the semicolon.
When the page loads, the script only hands the function over to the button; it doesn't run it. The function runs later, every time someone clicks the button: on the first click, on the second, and so on. Such a function is called an event handler.
The handler can also be an arrow function:
helloButton.addEventListener("click", () => {
message.textContent = "Hello!";
});Or a function you've defined before, passed by its name:
function sayHello() {
message.textContent = "Hello!";
}
helloButton.addEventListener("click", sayHello);Watch out for a typical mistake: addEventListener("click", sayHello()). With the parentheses, sayHello() is called right away, when the page loads, and addEventListener() gets what the function returned (undefined) instead of the function. There's no error, but the message appears before anyone clicks, and clicking does nothing. Pass the function without parentheses: the browser calls it itself, on every click.
Instructions
When greetButton is clicked, change the text of message to Nice to meet you!. Use addEventListener() with function () { ... }. Then try the button in the page.
When darkModeButton is clicked, toggle the class dark on page (the body element) with classList.toggle(). Write the handler as an arrow function this time. The first click makes the page dark, the next one light again.
Start programming for free
5/10