Events

Events are used to signal that something in the DOM has happened. Some events are user-generated, such as mouse or keyboard events, while others are generated by side effects such as videos being paused or an animation that has finished running.

Click

The most intuitive event is perhaps the click event. It is fired when a user clicks on an element inside the DOM. Events are passed as arguments to the click handler.

Let's alert a string when a user presses the Howdy button.

<html>
    <button id="greeting">Howdy</button>
</html>

To receive the click event when the user press Howdy we need to register an event listener. Listeners are functions that are scheduled to run when an event is fired. Just like setTimeout and setInterval.

const greetingButton = document.getElementById('greeting');

First we select the element that we want to listen for the event on.

greetingButton.addEventListener('click', (event) => {
    alert('... partner!');
});

Next we add an event listener that alerts our greeting when the event is fired.

Keypress

Another class of events that are typically fired are the ones associated with keypresses. A keypress usually fires the following events:

  1. When the key is first depressed, the keydown event is sent.

  2. If the key is not a modifier key (Shift etc.), the keypress event is sent.

  3. When the user releases the key, the keyup event is sent.

Each key has a unique keyCode property that represents it. We use the keyCode to determine which key was pressed.

Imagine that we want to alert when one of the arrow keys (, , , ) are pressed down (keydown) anywhere within the DOM.

document.addEventListener('keydown', (event) => {
    if (event.keyCode > 36 && event.keyCode < 41) {
        alert\('You pressed an arrow key.'\);  
    }
});

We register an event handler that can distinguish between arrow keys from all the other keys. To do so we check if the keyCode on the event lies between 36 and 41.

Last updated