Sometimes we load most of the page content using ajax dynamically. But this rendered html content generally does not bind with already defined events. But for making those events working, we need to rebind those events.
There are 2 ways of event binding on dynamically created elements :
1. This one is very simple and easy understood way. In this, first we load the content and after loading we bind the event under that.
1 2 3 4 5 | jQuery('div.pure_text').load('test.php',function(){ $('.edit').click(function(){ // code here }) }) |
Here, we are loading content from test.php file into a div class named ‘pure_text’. inside load callback we are binding click event of an element which has ‘edit’ named class.
It has one drawback that we need to rewrite the code if it is already written for preloaded content.
2. In this, we can write the code for event binding once before its loading.
As of jQuery 1.7 you should use jQuery.fn.on:
1 2 3 | $(staticAncestors).on(eventName, dynamicChild, function() { // write code here }); |
staticAncestors : It is an element which is already loaded/rendered into the page.
On :- It is jquery function for binding an event in latest jquery.
eventName :- Event for which we want to bind the element like click, focus, hover, mouseenter
dynamicChild :- It can be any type of selector which will be rendered/loaded in dynamically loaded content or preloaded content.
Callback :- It’s a callback function which is executed on the event.
Prior to this, the recommended approach was to use live():
1 | $(selector).live( eventName, function(){} ); |
However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:
1 | $(selector).live( eventName, function(){} ); |
… can be replaced with the following on() signature:
1 | $(document).on( eventName, selector, function(){} ); |
So what if we want to use latest jquery with old code. We can not update all of our prewritten code.
But even after deprecating the live in latest jQuery versions, we can use it by using jquery Migrate plugin. only need to include the jquery migrate plugin in the head tag before loading other javascript files or jquery code.