confetti on a party

Event delegation in jQuery using .on

With jQuery it is easy to attach event handlers to a DOM element using the ‘on’ method. Here we look at the click event, but the following also holds for other event types. Here, the click event is added to all DOM elements with class ‘button’ like this

$('.button').on('click', function(){
    console.log('Yeah, you clicked the button!');
});

Attaching the click event like this only works for DOM elements available on the page at the moment of binding the click handler to the button. Hence, you typically do this after initial page load. To make sure the page is fully loaded you either put your jQuery code inside a $(document).ready function, or you put your JS code just before the closing body tag.

So far so good. Now suppose a list of buttons (each with class ‘button’) is added to the page after some user interaction. Even though the buttons have the class correct, clicking them will not yield a ‘Yeah you clicked the button’ message in the console.

Event delegation

Luckily, with event delegation we can solve this issue. To make it work we have to do the following:

  1. Attach the click handler to the body (or another element high enough in the DOM hierarchy to be sure it is on the page when we attach the event)
  2. Use an extra parameter in the .on call: the first argument is the event type (click) and the second is a selector to which the event will be attached.

Knowing this, the correct way to bind the click event for all (current and future) buttons with class ‘button’ is:

$('body').on('click', '.button', function(){
    console.log('Yeah, button clicked through event delegation!');
});

Mijn Twitter profiel Mijn Facebook profiel
Pim Hooghiemstra Webdeveloper and founder of PLint-sites. Loves to build complex webapplications using Vue and Laravel! All posts
View all posts by Pim Hooghiemstra

Leave a Reply

Your email address will not be published.