225 Event bubbling and delegation [1.5d]

Updated . Posted . Visible to the public.

DOM events travel up the tree from the element where they happened. Understanding this lets you handle events for many elements with a single listener, including elements that don't exist yet.

Important

Work on this lesson in advisor mode.

Learning goals

  • You can explain how a DOM event travels through the tree — capturing, target, bubbling — and which listeners see it in which order.
  • You can explain the difference between event.target and event.currentTarget.
  • You can explain what stopPropagation(), stopImmediatePropagation() and preventDefault() each do, and pick the right one for a situation.
  • You can handle events for many elements with a single listener on an ancestor (event delegation), including elements that are added after the page loaded.
  • You can weigh many individual handlers against one delegated handler: number of handlers, unnecessary target checks, ability to stop propagation, dynamically created elements.

Three ways to handle a click

You have the following HTML structure:

<div class='some-class'>...</div>

<div class='container'>
  <div class='my-target'>...</div>
  <div class='my-target'>...</div>
  <div class='my-target'>...</div>
</div>

<div class='other-class'>...</div>

If you want to run Javascript code whenever someone clicks on a <div class='my-target'>...</div>, you can do this in three different ways:

function code(event) {
  alert("Someone clicked on .my-target!");
}

document.addEventListener('click', function(event) {
  if (event.target.closest('.my-target')) {
    code(event)
  }
})

document.querySelector('.container').addEventListener('click', function(event) {
  if (event.target.closest('.my-target')) {
    code(event)
  }
})

for (let target of document.querySelectorAll('.my-target')) {
  target.addEventListener('click', code)
}

Use the resources below and talk with your mentor to find out the pros and cons of each approach. You should at least talk about the following issues and tradeoffs:

  • Registering many handlers vs. having many unnecessary target element checks in JavaScript.
  • Ability to stop event propagation.
  • Ability to work with elements that are created programmatically after the initial page load.

Furthermore, you should gain a solid understanding about the differences of stopPropagation(), stopImmediatePropagation() and preventDefault().

Resources

Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.

Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.

Exercises

Whac-A-Mole

We will implement a simplified version of Whac-A-Mole Show archive.org snapshot in HTML and Javascript.

Start with this HTML structure:

<div class="arena">
  <div class="mole"></div>
  <div class="mole"></div>
  <div class="mole"></div>
  <div class="mole"></div>
  <div class="mole"></div>
  <div class="mole"></div>
</div>

<div class="score">
</div>

<div class="time-left">
</div>

Now add some Javascript to implement the following game:

  • The player's score is displayed on the screen. The player starts with a score of 0.
  • The arena randomly shows 1 out of 6 total moles.
  • The aim of the game is to click on the currently visible mole as fast as possible.
  • Whenever the user clicks within the arena, the moles are randomly hidden or shown.
  • When the user clicks on a visible mole, she gets 10 points added to her score. When the user clicks on a hidden mole, she gets 25 points substracted from her score.
  • The player has 30 seconds to rack up as many point as she can. The remaining time is shown next to the score.
  • When the time is up, a Javascript alert pops up, informing the player about her final score. Pressing "OK" starts another game.

Build two different implementations of this:

  1. Add an event handler to each mole separately
  2. Once the game works, use event delegation to minimize the number of event handlers to as low a number as possible. How low can you get? What pieces of Javascript can we not implement using delegation?
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-09-09 08:55)