Wednesday, October 30, 2013

Dynamically created element event binding in jQuery

Many of the code had been re-written and many methods were deprecated since the release of jQuery 1.7. Now the current stable release is jQuery v1.10.2. You can see more details here. In earlier versions we could bind an event to an HTML element via methods such as .bind(), .live() etc.  As of jQuery version 1.7 these methods were deprecated and .on() methods was introduced.

The .on() method provides all the functionality required for attaching event handlers. Here i am going to give two examples one for implementing the .bind() method functionality and the another for implementing the .live() method.

Example for implementing the .bind() feature

In this section we are going to see an example for binding a click event for a DIV element via .on() method.

HTML
<div class='div1'></div>

We could bind an event to this div with the following code:

$('.div1').on('click',function(){
  alert('Hello World!');
}); 

Also note that this example will not fire the event for dynamically created elements.  

Example for implementing the .live() feature

.live() method was introduced in an attempt to simplify attaching event handlers for all elements via a selector, that are present now and in future( i.e dynamically created elements).   For this example suppose that the div with class name "div1" was created dynamically.

HTML
<div class='mainDiv'>
   <div class='div1'></div>
</div>

With live  jQuery.live() method one could attach an event to this div with the following code:

$('.div1').live('click',function(){
  alert('Hello World!');
}); 

The .live() code above is simple and easy to implement. But as the .live() method is deprecated and the .on() method is introduced things become a little bit different. Unlike .live() method , .on() is a more generic event handler method. We can use the .on() method to implement the .live() feature but with a small difference. You have explicitly provide a container for the element you wish to attach the event.
So to implment the .live() feature with the .on() method, the code would be:

 $('.mainDiv').on('click','.div1',function(){
  alert('Hello World!');
}); 

Here .mainDiv is the container which holds the dynamically created element.  In general one could use 

$(document.body).on('click','.div1',function(){
     alert('Hello World!');
});

But it would be better to provide an element that is closer to the HTML heirarchy( in our example mainDiv).

To remove events bound with .on() event we could use .off() method. Also .die() method can be used to remove event handlers previously attached using .live() method from the elements.

No comments:

Post a Comment