Lesson 14 of 199:53 video

JavaScript event listeners

How a page reacts to a click or a key: addEventListener and the function you hand it, the event object, event bubbling and event delegation, 'this' and closures in a listener, keydown and input events, and preventDefault for the browser's default actions.

In this lesson

  1. 0:00 Intro
  2. 1:05 Listening for a click
  3. 1:55 The event object
  4. 2:30 Bubbling
  5. 3:19 Event delegation
  6. 4:05 Who calls a listener
  7. 4:50 this in a listener
  8. 5:34 A listener that remembers
  9. 6:21 Removing a listener
  10. 6:56 Keyboard events
  11. 7:37 Input events
  12. 8:17 Default actions
  13. 9:13 In one line
  14. 9:29 Next time

Here’s a web page for a rocket called Kestrel, kestrel.html. It has a heading, a Launch button, a fuel gauge and a crew list:

<!DOCTYPE html>
<html>
  <head>
    <title>Kestrel</title>
    <link rel="stylesheet" href="kestrel.css">
  </head>
  <body>
    <h1>Kestrel: on the pad</h1>
    <button>Launch</button>
    <progress id="fuel" value="80" max="100"></progress>
    <ul>
      <li>Ada</li>
      <li>Lee</li>
      <li>Omar</li>
    </ul>
    <script src="mission.js"></script>
  </body>
</html>

It loads a stylesheet, kestrel.css, which holds one rule:

.aboard { color: green; }

And it loads a script, mission.js:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", launch);

Open the page and press the button. The heading reads Kestrel: liftoff. Now put the same button inside a form, and change nothing else:

<form>
  <button>Launch</button>
</form>

Press it again. The heading changes, and before you can read it, the page loads again and says on the pad. Nobody pressed reload, and nothing in the script asks for one. So who reloaded the page?

By the end of this lesson you’ll know how a page listens (you hand the browser a function, and the browser calls it when the event happens), what the event object is and the path it travels up the page’s tree, and what the browser does on its own once your listeners have run. That last part is the answer.

To follow along, save the three files in one folder and open kestrel.html in a browser. Each example below is the whole of mission.js: replace what’s in it, save, reload the page, and press what it says. What a listener prints shows in the console of the browser’s developer tools.

Listening for a click

Start with the line that works, the last line of mission.js: button.addEventListener("click", launch);. It has three parts. The element is the button, found with querySelector. Then the event’s name, as a string: "click". Then a function, launch, which changes the heading.

addEventListener doesn’t run that function. It stores it on the button, in a list of functions to call when a click arrives. Each one is called a listener; you’ll also see the name event handler. A button can hold several, and the browser calls them in the order you added them.

Now look at what’s missing: there are no parentheses after launch. You aren’t calling the function. You’re handing it to the browser, for the browser to call. Add them, and the line means something else:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", launch());

Now launch runs right away, while the page loads, and the heading says liftoff before anyone has clicked. What addEventListener gets is the value launch() returned: undefined. It accepts that without complaint and stores nothing. You get no error, and a button that does nothing.

The event’s name is a string, so a typo isn’t an error either. A listener for "clik" is added, and it never runs. Older code sets button.onclick = launch instead. That property holds one function, so a second assignment replaces the first.

The event object

When the browser calls a listener, it passes one argument: an object that describes what just happened. This is the event object, and most code names the parameter event (you’ll also see e):

const button = document.querySelector("button");

button.addEventListener("click", (event) => {
  console.log(event.type); // click
  console.log(event.target.textContent); // Launch
  console.log(event.shiftKey); // false
});

Its type is the event’s name, here "click". Its target is the element the click landed on, here the button. A click also records where the pointer was, in event.clientX and event.clientY (its distance in pixels from the window’s left edge and from its top), and whether a key like Shift was held down. Press again with Shift held, and event.shiftKey is true.

Every click gets a new event object. And each kind of event brings details of its own: a key press, as you’ll see, says which key it was. Chrome’s console calls a click’s object a PointerEvent, and lists dozens more properties if you log the whole thing.

Bubbling

A click doesn’t stay where it lands. Put one listener on the crew list, the whole list, and click one name:

const list = document.querySelector("ul");

list.addEventListener("click", (event) => {
  console.log(event.target.textContent); // Lee
  console.log(event.currentTarget === list); // true
});

Click Lee, and the listener runs. The list heard a click on one of its items, because the browser sends every click up the DOM, the tree of elements it built from the page. It starts at the element under the pointer, Lee’s list item, and calls any click listeners there. Then it moves up to the parent, the list, and calls the listeners there. Then the body, the html element, document, which is the tree’s root, and one stop past it, window.

That climb is called bubbling. One event object makes the whole trip, and two of its properties tell you where it is:

  • event.target never changes. It’s the element the click landed on: Lee’s list item.
  • event.currentTarget names the element whose listener is running now: here, the list.

Before the climb, the event also travels down from the top to the element, which is called the capture phase. A listener added with { capture: true } as a third argument runs on the way down. And a few events don’t bubble at all: focus is one.

Event delegation

Bubbling solves a real problem. Say a click on a crew member should mark them as aboard. You could give each list item its own listener:

const items = document.querySelectorAll("li");

for (const item of items) {
  item.addEventListener("click", () => {
    item.classList.toggle("aboard");
  });
}

const zoe = document.createElement("li");
zoe.textContent = "Zoe";
document.querySelector("ul").append(zoe);

Ada, Lee and Omar turn green when you click them. But the script then adds a fourth crew member, Zoe, and clicking Zoe does nothing. The loop ran before Zoe existed, so Zoe never got a listener.

So add one listener to the list instead. A click on any item bubbles up to it, and event.target says which item it was:

const list = document.querySelector("ul");

list.addEventListener("click", (event) => {
  if (event.target.matches("li")) {
    event.target.classList.toggle("aboard");
  }
});

const zoe = document.createElement("li");
zoe.textContent = "Zoe";
list.append(zoe);

matches takes a selector, as querySelector does, and answers true or false. Now Zoe turns green too, though she arrived after the listener did. That’s event delegation: one listener on a parent that answers for all its children.

The check matters. Without it, a click on the list’s own space between two names makes the list itself the target, and the class goes on the list, which turns every name green. And if an item held other elements, a click landing on one of those makes it the target; event.target.closest("li") finds the item from any element inside it.

Who calls a listener

So who calls a listener, and when? Watch the script run. It finds the button, hands launch to addEventListener, and ends. Now nothing is running. The call stack, which holds the functions being run, is empty.

Then someone clicks. The browser puts the click in the task queue, where work waits its turn. The event loop, which watches for an empty stack, takes it from the queue and calls the listeners. launch runs. Every click makes the same trip.

There’s one stack, because your JavaScript runs on a single thread, so it does one thing at a time. If a listener takes three seconds, the next click waits in the queue until it’s done, and the page freezes in the meantime. While a listener runs, the browser can’t even redraw the page.

Not every event starts with a person. DOMContentLoaded fires on document once the browser has built the tree from the file, and a timer, a reply from a server or a finished image all arrive as events too.

this in a listener

That call has a catch. Here’s a rocket object, with a launch method that reads this.fuel:

const button = document.querySelector("button");

const rocket = {
  name: "Kestrel",
  fuel: 80,
  launch() {
    console.log("Liftoff with " + this.fuel + "% fuel");
  },
};

button.addEventListener("click", rocket.launch); // Liftoff with undefined% fuel

Inside a method, this is whatever was left of the dot when it was called. But rocket.launch was handed over without its object, and when the browser calls a listener, it sets this to event.currentTarget, the element the listener was added to. Here that’s the button, and a button has no fuel.

The fix is to hand over an arrow function that makes the call itself, with the rocket left of the dot:

const button = document.querySelector("button");

const rocket = {
  name: "Kestrel",
  fuel: 80,
  launch() {
    console.log("Liftoff with " + this.fuel + "% fuel");
  },
};

button.addEventListener("click", () => rocket.launch()); // Liftoff with 80% fuel

rocket.launch.bind(rocket) works too. And remember that an arrow function has no this of its own: in a listener written as one, this isn’t the element, so use event.currentTarget.

A listener that remembers

What a listener does keep is its closure: the variables around it where it was written. Here’s a function called makeCountdown. It holds a number in a variable, seconds, and returns a function that prints the number and takes one off:

const button = document.querySelector("button");

function makeCountdown(from) {
  let seconds = from;
  return function () {
    console.log(seconds);
    seconds = seconds - 1;
  };
}

const tick = makeCountdown(3);
button.addEventListener("click", tick);
// 3
// 2
// 1

Click three times, and you get 3, 2, 1. Between clicks none of your code is running, and makeCountdown finished long ago. The variable is still there, because the listener still holds a link to it.

Turn the countdown around, and you get a button that counts its own clicks:

const button = document.querySelector("button");

function makeClickCounter() {
  let clicks = 0;
  return () => {
    clicks = clicks + 1;
    button.textContent = "Clicks: " + clicks;
  };
}

button.addEventListener("click", makeClickCounter());

Parentheses, this time: makeClickCounter runs once, now, and the function it returns is the listener. The button reads Clicks: 1, Clicks: 2, Clicks: 3. A global variable could hold that count too, but then any code on the page could change it. This count, only the listener can reach.

Removing a listener

A rocket lifts off once. To stop listening, there’s removeEventListener. Give it the event’s name and the listener:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", launch);
button.removeEventListener("click", launch);

It has to be the very same function you added, which is why a listener you mean to remove needs a name. Write an arrow function out a second time and you’ve made a new function:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", () => launch());
button.removeEventListener("click", () => launch());

Nothing is removed, and nothing warns you: the button still launches. Two functions that look alike are still two functions, and (() => launch()) === (() => launch()) is false.

For a listener that should run a single time, there’s a shortcut. Pass addEventListener a third argument, an object with once set to true:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", launch, { once: true });

After the first click, the browser removes the listener for you.

Keyboard events

Keys work the same way. Pressing one fires an event called keydown. It goes to whichever element has focus: the field you’re typing in, or the button you tabbed to. If nothing has focus, it goes to the body. Then it bubbles, so one listener on document hears every key press on the page.

A keydown’s event object carries a property that a click’s doesn’t: key, the key’s name as a string. The letter l in lower case is "l". The others are named: "Enter", "Escape", "ArrowUp", "Shift". So a keyboard shortcut takes one comparison:

const heading = document.querySelector("h1");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

document.addEventListener("keydown", (event) => {
  if (event.key === "l") {
    launch();
  }
});

Click on the page’s background so the button doesn’t have focus, then press l. With Shift held, the key is "L", a different string, and nothing launches. A shortcut on document also fires while someone types in a text field, so a real one checks event.target first. And a focused button already answers Enter and the space bar with a click of its own.

Input events

A text field fires an event called input every time its contents change: a character typed, one deleted, text pasted in. What the field holds is in its value property. Add a field for Kestrel’s fuel to the page, after the gauge:

<input id="amount" type="number">

Then copy the field’s value to the gauge on every input event:

const field = document.querySelector("#amount");
const gauge = document.querySelector("#fuel");

field.addEventListener("input", () => {
  gauge.value = Number(field.value);
  console.log(field.value, typeof field.value);
});
// 9 string
// 90 string

Type 9, then 0, and the bar follows as you type. A field’s value is always a string, even in a field made for numbers. With ninety typed, field.value is the string "90", so field.value + 5 is "905": the plus sign joins them as text. Convert the value with Number first, as the listener does, and Number(field.value) + 5 is 95. A number field also has valueAsNumber, which is already a number.

A second event, change, fires once instead: when you leave the field after changing it.

Default actions

Which brings us back to the form we started with, and the page that reloaded. The click did reach the listener, and launch did change the heading. But for some events, the browser has a reaction of its own, called the default action. Click a link, and it follows the link. Click a checkbox, and it checks the box. Click a button inside a form, and once the listeners have run, it submits the form: it sends the form’s fields to the page’s own address, and loads what comes back. A new page, with a new tree, built from the file. Back on the pad. The address bar shows it: kestrel.html?, a form sent with no fields in it.

The event object can call that off, with a method named preventDefault. Call it in the listener, and the browser skips its own step:

const heading = document.querySelector("h1");
const button = document.querySelector("button");

function launch() {
  heading.textContent = "Kestrel: liftoff";
}

button.addEventListener("click", (event) => {
  event.preventDefault();
  launch();
});

Run that with the button inside the form. Liftoff, and this time it stays.

Two more ways to the same place. A button in a form submits it unless its tag says type="button". And a form has an event of its own, submit, fired on the form, both for its button and for Enter in a field; preventDefault works there too. One thing to keep apart: preventDefault stops the browser’s action, not the climb, and stopPropagation stops the climb, not the action.

Summary

  • addEventListener takes an event’s name and a function. It stores the function, and the browser calls it when the event happens. Hand over the function itself, launch, not the result of calling it, launch().
  • The browser calls a listener with an event object: its type, its target, and details such as clientX, shiftKey or key.
  • An event lands on one element and then bubbles up through every element above it to document. target stays the element it landed on; currentTarget is the element whose listener is running.
  • One listener on a parent can answer for all its children, including ones added later: that’s event delegation.
  • Listeners are called by the event loop, one at a time, from an empty call stack, so a slow listener freezes the page.
  • In a listener, this is the element, so hand a method over inside an arrow function. A listener keeps its closure.
  • removeEventListener needs the same function that was added; { once: true } removes a listener after one call.
  • keydown and event.key for keys, input and value for fields, and a field’s value is always a string.
  • After the listeners, the browser takes its default action, unless a listener calls event.preventDefault().

Next in this series: sending for data without leaving the page, with fetch and JSON.

Video transcript

Intro

Here's a page for a rocket called Kestrel, with a Launch button under the heading. One line of JavaScript listens for a click on that button. Press it, and the heading reads: Kestrel, liftoff. Now put the same button inside a form, and change nothing else. Press it again. The heading changes, and before you can read it, the page reloads. Back on the pad. Nobody pressed reload, and nothing in the script asks for one. So who reloaded the page? Today, we find out.

By the end of this video, you'll understand three things. One: how a page listens: you hand the browser a function with addEventListener, and the browser calls it when the event happens. Two: the event object, and the path it travels up the page's tree of elements, called bubbling. Three: the browser's own reaction to an event, its default action: why that page reloaded, and how to stop it.

Listening for a click

Start with the line that works. It has three parts. An element: the button, found with querySelector. An event's name, as a string: click. And a function: launch, which changes the heading. addEventListener doesn't run that function. It stores it on the button, in a list of functions to call when a click arrives. Each one is called a listener, or an event handler. Now look at what's missing: there are no parentheses after launch. You aren't calling the function. You're handing it to the browser, for the browser to call. Add the parentheses, and launch runs right away, while the page loads. The heading says liftoff before anyone has clicked, and what the button gets is the value launch returned: undefined. No error, and a button that does nothing.

The event object

When the browser calls a listener, it passes one argument: an object that describes what just happened. This is the event object. Most code names the parameter event. Its type is the event's name. Here that's click. Its target is the element the click landed on. Here that's the button. A click also records where the pointer was in clientX and clientY, and whether a key like Shift was held down. Every click gets a new event object. And each kind of event brings details of its own.

Bubbling

A click doesn't stay where it lands. Put a click listener on the crew list, the whole list, and click one name: Lee. The listener runs. The list heard a click on one of its items, because the browser sends every click up the DOM, the tree of elements it built from the page. It starts at the element under the pointer, Lee's list item, and calls any click listeners there. Then it moves up to the parent, the list, and calls the listeners there. Then the body, and on up to document, at the top. That climb is called bubbling. One event object makes the whole trip, and two of its properties tell you where it is. target never changes: it's the element the click landed on. currentTarget is the element whose listener is running now.

Event delegation

Bubbling solves a real problem. Say a click on a crew member should mark them as aboard. You could loop over the three list items and give each one a listener. But then the script adds a fourth crew member: Zoe. Click Zoe and nothing happens. The loop ran before Zoe existed, so Zoe never got a listener. So add one listener to the list instead. A click on any item bubbles up to it. And event dot target says which item it was. Check that the target is a list item with matches. Then toggle the class aboard on it. Ada. Omar. And Zoe, who arrived after the listener did. That's event delegation: one listener on a parent that answers for all its children.

Who calls a listener

So who calls a listener, and when? Watch the script run. It finds the button, hands launch to addEventListener, and ends. Now nothing is running. The call stack, which holds the functions being run, is empty. Then someone clicks. The browser puts the click in the task queue, where work waits its turn. And the event loop, which watches for an empty stack, takes it from the queue and calls the listeners. launch runs. Every click makes the same trip. There's one stack, because your JavaScript runs on a single thread, so it does one thing at a time. If a listener takes three seconds, the next click waits in the queue for it, and the page freezes until it's done.

this in a listener

That call has a catch. Here's a rocket object, with a launch method that reads this dot fuel. Inside a method, this is whatever was left of the dot when it was called. Hand rocket dot launch to addEventListener, click, and you get: Liftoff with undefined percent fuel. The method was handed over without its object. And when the browser calls a listener, it sets this to currentTarget, the element the listener was added to. Here, that's the button, and a button has no fuel. The fix is to hand over an arrow function that makes the call itself: rocket dot launch, with the rocket left of the dot. Liftoff with eighty percent fuel.

A listener that remembers

What a listener does keep is its closure: the variables around it where it was written. Here's a function called makeCountdown. It holds a number in a variable, seconds, and returns a function that prints the number and takes one off. Call makeCountdown with three, and hand the function it returns to the button. Click: three. Click: two. Click: one. Between clicks, none of your code is running, and makeCountdown finished long ago. The variable is still there, because the listener still holds a link to it. Turn the countdown around, and you get a button that counts its own clicks. A global variable could hold that count too, but then any code on the page could change it. This count, only the listener can reach.

Removing a listener

A rocket lifts off once. To stop listening there's removeEventListener. Give it the event's name and the listener. It has to be the very same function you added. Write an arrow function out a second time and you've made a new function. Nothing is removed and nothing warns you. That's a good reason to give a listener a name. For a listener that should run a single time there's a shortcut. Pass addEventListener a third argument: an object with once set to true. After the first click, the browser removes the listener for you.

Keyboard events

Keys work the same way. Pressing one fires an event called keydown. It goes to whichever element has focus. That's the field you're typing in or the button you tabbed to. If nothing has focus it goes to the body. Then it bubbles. So one listener on document hears every key press on the page. A keydown's event object carries a property that a click's doesn't. It's called key and it holds the key's name as a string. The letter l in lower case. Enter. Escape. ArrowUp. So a keyboard shortcut takes one comparison: if event dot key is the letter l, launch.

Input events

A text field fires an event called input. It fires every time the field's contents change: a character typed, one deleted, text pasted in. What the field holds is in its value property. Here's a field for Kestrel's fuel. On every input event, the listener copies the field's value to the fuel gauge, and the bar follows as you type. One thing to know: a field's value is always a string, even in a field made for numbers. Type ninety, and you get the string ninety. Add five to that, and the plus sign joins them as text: nine, zero, five. Convert the value with Number first.

Default actions

Which brings us back to the form we started with, and the page that reloaded. The click did reach the listener, and launch did change the heading. But for some events, the browser has a reaction of its own, called the default action. Click a link, and it follows the link. Click a checkbox, and it checks the box. Click a button inside a form, and once the listeners have run, it submits the form: it sends the form's fields to the page's own address, and loads what comes back. A new page, with a new tree, built from the file. Back on the pad. The event object can call that off, with a method named preventDefault. Call it in the listener, and the browser skips its own step. Liftoff, and this time it stays.

In one line

That's events in one line: you hand the browser a function with addEventListener; the browser calls it with an event object, at the element the event landed on, then at each element above it; and then it takes its own default action, unless you prevent it.

Next time

Next time, we send for data without leaving the page: fetch, which asks a server for data and hands back a promise, and JSON, the text that data travels as.

Learn more