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:

document.getElementById('clickThisButton').addEventListener('click', /* function goes here */);

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:

<body>
    <!--All of our HTML code will go here-->
    <button id="clickThisButton">I want to be clicked</button>

    <script type="text/javascript">
        /* All of our JavaScript code will go here */
        document.getElementById('clickThisButton').addEventListener('click', () => {
            console.log('I was clicked!');
        });
    </script>
</body>

Clicking the button should produce a message in the console:

Button 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!

document.getElementById('clickThisButton').addEventListener('click', (details) => {
    console.log(details);
});

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.

<script type="text/javascript">
    /* All of our JavaScript code will go here */
  document.getElementById('clickThisButton').addEventListener('click', (details) => {
     details.target.style.backgroundColor = 'red';
});
</script>

Now when you click the button, the button's background color should turn red!

Last updated