Event delegation in jQuery using .on

With jQuery it is easy to attach event handlers to a DOM element. Typical events are a click, a hover or a keypress. Given the DOM element with ID ‘button’, you can attach the click event handler as follows:

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

This way of attaching events to DOM elements only works if the DOM element is available at the moment you bind it, often once the page is fully loaded when wrapped in a $(document).ready function:

$(document).ready(function(){
    $("#button").hover(function(){
       console.log('Mouse enter...');
    }, function(){
       console.log('... and mouse leave again');
    }); 
}) 

Now suppose we have to add some DOM nodes after some user interaction, for example a list of links is added to the page after clicking a button. The former click or hover event will not work: nothing happens, because the list of links was not available when the event handler was bound. Luckily, with event delegation we can solve this issue.

Note that $().click is a short form of $().on(‘click’). With $().on we can bind any standard or custom event to the DOM. However, the .on function takes an optional argument essential for event delegation. It works like this

$("body").on("click", "ul li a", function(){
    console.log('Yeah, a link clicked through event delegation!');
});

How does event delegation work?

Event delegation depends strongly on the availability of the jQuery selector at runtime. Since the <body> element always exists, it is an easy victim. The selector is followed by the .on function and the click event is attached, but not to the body! It is attached to each link in all lists, those that were there already on pageload and the links created at a later time after user interaction.

It is also possible to unbind the event from the DOM again. Then you use the $().off() function.


Mijn Twitter profiel Mijn Facebook profiel
Pim Hooghiemstra Webdeveloper and founder of PLint-sites. Loves to build complex webapplications using Vue and Laravel! Latest post
Adding Workbox to a @vue/cli PWA

Leave a Reply

Your email address will not be published. Required fields are marked *