Posted almost 3 years ago. Visible to the public.

Event bubbling and delegation


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:

code = function(event) { alert("Someone clicked on .my-target!"); }; $(document).on('click', '.my-target', code); $('.container').on('click', '.my-target', code); $('.my-target').on('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 jQuery run many unnecessary checks in Javascript.
  • Ability to stop event propagation.
  • When we can't use event delegation (e.g. when we want to manipulate an event when it appears)
  • How do you unregister an event handler? When is this necessary? Why is it usually not necessary?


Exercise: Whac-A-Mole

We will implement a simplified version of Whac-A-Mole 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 up to 6 moles.
  • The aim of the game is to click on visible moles 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?

Author of this card:

Henning Koch
Last edit:
over 1 year ago
by Henning Koch
Posted by Henning Koch to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more