Learn what is the event delegation in jQuery and how to use in your projects.

The event delegation in javascript allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent.

If there are many elements inside one parent, and you want to handle events on them, we don'want to bind handlers to each element. Instead,we bind the single handler to their parent as a good practice.

When you create a dom object dinamically and you need to attach the event to an object that doesn't exist yet but it will.

Understand it easily with the following example, an ajax will be executed and will append divs with class "myDivision" in our document,we want that everytime the user clicks a myDivision div something happend. If you declare the listener like this when the document is ready :

$(".myDivision").click(function(){
    //Binded event to our .myDivision objects 
});

You will notice that when the ajax call is executed and divs are added to our document, nothing will happen on the click ! But why ?

Simple, when the click function is executed, No object with class myDivision exists yet so no listener will be binded.

You would create a hidden div with that class and the listener will be binded , but when the ajax call is executed again and more myDivision divs are added to the DOM, will not work neither !

So we need to handle event delegation to don't add a click listener for every .myDivision object that we add dinamycally in the document like this :

$(document).on("click",".myDivision", function(){
    //Execute something 
});

The event delegation is very easy to understand, a listener is added to the parent container of our objects and it will manage the listeners of all the child target items.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors