Events
Now let's talk about making stuff happen when we want it to, such as when a button gets clicked! Having a function run when a button is clicked is one of the most common actions on a web page, but how would we set this up?
We need to fire some sort of "signal" when a button is clicked. When our JavaScript receives that "signal", then it will run the function. We call these "events". Common events might include when a user does one or more of the following:
clicks the mouse
presses a key on the keyboard
resizes the browser window
hovers the mouse over something
when a form gets submitted
when the page finishes loading...etc
There are tons of events happening ALL THE TIME, we just need to listen for them!
This is where "event listeners" come into play. In JavaScript, an "event listener" waits for an event to happen on an element (such as waiting for a click event on a button or a keypress event on an input field), and then it runs a particular function.
The syntax for an event listener is:
Here the function can either be a named function or an anonymous function. Let's walk through an example. Build an HTML button and duplicate the following JavaScript:
Clicking the button should produce a message in the console:
Better yet, each event has details about the event! Make our function accept an argument, and then print that to the console, so we can see what kind of information that "click" event gives us!
Take a look at your console and inspect the response. It's pretty long! There's a ton of information there, way more than any normal developer uses. Most often, you will be interested in the target
property. Let's change the target's background color to be red.
Now when you click the button, the button's background color should turn red!
Last updated