Event delegation in jQuery using .on

Pim Hooghiemstra
PLint-sites
Published in
2 min readFeb 14, 2013

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, i.e., once the page is fully loaded or 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 add some DOM nodes after a 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 $(selector).click(function(){}) is a short form of $(selector).on('click', function(){}). With $(selector).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 the selector ul li a, that is, to each link in all lists, those that were already there when the page loaded initially 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 $(selector).off() function.

Originally published at www.blog.plint-sites.nl on February 14, 2013.

--

--

Pim Hooghiemstra
PLint-sites

Love to build Laravel + Vue applications! Founder of PLint-sites. https://plint-sites.nl