Some models of programming require you to choreograph the computation from start to finish in a main function. This is not typically what you see in browser-based scripts in which the viewer drives the consumption of the content. Instead, you schedule your code to be run when certain events happen, including mouse clicks, window resizing, and keypresses.
A function that runs when an event happens is an event listener. You register an event listener by calling the
addEventListener method of the element or object that triggers the event. For example, here is a page with two buttons that change the background color of the page when clicked on:
Notice how only the names of the
blue functions are passed as parameters to
addEventListener. If you had included parentheses after their names, then you would be calling these functions and passing their returned values to
addEventListener. You want to pass the functions themselves, so you leave off the parentheses. Try adding parentheses after these names.
You normally set the background color in a stylesheet, but styles can also be set programmatically through an element's
All event listeners receive as a parameter an event object from the browser that gives information about the event. For instance, a mouse wheel event provides information about how much the wheel was scrolled:
Try opening your developer tools and scrolling the mouse wheel over the image. What values do you see when you scroll up? When your scroll down?
Notice how the window still scrolls as you scroll on the image. That's because the scroll event bubbles up the page structure, and the window itself has an event listener that moves the page up and down. To stop a builtin event listener from running, you call
Suppose you want the image to be zoomed in or out on wheel events. You add a scale factor that grows and shrinks on each wheel event and use it to apply a scale transform to the image:
scale is declared using the keyword
picture is declared using
let variable may be reassigned, but a
const variable may not. You should favor
const to prevent accidental overwrites and to communicate that a variable will doggedly hang on to its value. In this case, however, you want
scale to be overwritten.
While an element's style can be set programmatically, you may prefer to define the alternate styles using a class selector and use event listeners to add or remove the class from an element. For example, suppose you are building a quizzing app and have this structure:
You want the answer to be hidden initially. When the button is clicked, you add the class
revealed to the answer element, which applies a new ruleset from the stylesheet:
classList provides several methods for modifying or querying an element's classes. Try modifying this page so that the viewer can hide the revealed answer.