jQuery - Event delegation

jQuery

In this tutorial we will learn about event delegation in jQuery.

Event delegation in jQuery is a process of adding an event handler to the parent element of the targeted elements. So, the parent element then delegates the event handler to the child elements.

Scenario

Lets say, we have a Topics page and there are 20 topics displayed in that page.

Each topic is enclosed inside a div having class "topic". When we click on the div the topic detail is shown.

Following is the HTML for the page.

<div id="topic-container">
  <div class="topic">
    <h3>Bootstrap</h3>
  </div>
  <div class="topic">
    <h3>CSS</h3>
  </div>
</div>

If you look at the above image you can see that we have a topics page having some topic displayed. We have a Plus (+) button to add new topic.

Add the click event handler

If we want to add the click event to the divs having class "topic" then we can write the following code.

$(".topic").on("click", function(){
  
  // topic detail code goes here...

});

And this code will add the click event to all the divs in the page having class "topic".

Problem

But, we have a problem in this approach.

We are saying that there are 20 topics so, by this approach we have to add the click event handler to the 20 divs having class "topic".

That is, travelling the entire page. Looking for the divs having class "topic". And adding the click event handler to the div.

And if the user adds a new topic then the click event handler will not be applied to the newly added div having class "topic".

This is because on() method will add the click event handler to all the divs having class "topic" in the page for that time when it was executed. And any new div having class "topic" appended later to the page will not get the click event handler.

on() method can't add event handlers to elements that are added later.

To solve this issue we use event delegation method.

Event delegation

In this case we add the event handler to the parent of the targeted elements. And we let the parent element delegate the event handler to the child elements.

In the following example we are adding the click event handler for the divs having class "topic" to its parent i.e., the div having id topic-container.

$("#topic-container").on("click", ".topic", function() {

  // add some click handling code here...

});

So, now if the user adds a new topic div inside the topic container div then the click event will be delegated to it.

Syntax

So, to add event handler to any element using on() method we use the following syntax.

$(selector).on(event, function() {
  // some code goes here...
});

Example

$(".topic").on("click", function() {
  // some code here...
});

And when we want to delegate the event we use the following on() method syntax.

$(selector).on(event, delegateSelector, function() {
  // some code goes here...
});

Example

$("#topic-container").on("click", ".topic", function() {
  // some code here...
});