How to bind events on ajax loaded content using jQuery?

How to bind events on ajax loaded content using jQuery?

Understanding Event Delegation #jQuery #jQueryEvent

In this article, I am going to explain how to bind event on content loaded by AJAX.

We need to use a technique called Event Delegation to attach event on dynamically / ajax loaded content.

Definition of Event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Here is a simple example to understand Event delegation

Normally we attach the event to a specific element using .on().

// Attach a directly bound event handler
$( "#listContainer a" ).on( "click", function( event ) {
   console.log( $( this ).text() );

Above bounded event will not work when a new dynamic element added. it because of Direct events are only attached to elements at the time the .on() a method is called.

To overcome this issue we can create a delegated event:

// Attach a delegated event handler
$( "#listContainer" ).on( "click",'a',function( event ) {
   console.log( $( this ).text() );

we have moved the a part from the selector to the second parameter position of the .on() method. We have now attached a single click event listener to our <ul> that will listen for clicks on its descendant anchors.

Summary ( Mentioned on jQuery site):

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

Happy Coding 🙂

Leave a Reply

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