How to use jQuery events on content loaded via AJAX

I am working on a project, where I have to perform some jQuery/Ajax events on contents loaded via Ajax.
I have search on Google and found a solution which is working for me. I am sharing it with you.

May be it would be helpful for you.


jQuery selectors select matching elements that exist in the DOM when the code is executed, and don't dynamically update. When you call a function, such as .click() to add event handler(s), it only adds them to those elements. When you do an AJAX call, and replace a section of your page, you're removing those elements with the event handlers bound to them and replacing them with new elements. Even if those elements would now match that selector they don't get the event handler bound because the code to do that has already executed.

Event handlers

Specifically for event handlers (i.e. .click()) you can use event delegation to get around this. The basic principle is that you bind an event handler to a static (exists when the page loads, doesn't ever get replaced) element which will contain all of your dynamic (AJAX loaded) content. You can read more about event delegation in the jQuery documentation.

For your click event handler, the updated code would look like this:

$(document).on('click', "#click", function () { 
$('#click').css({       
"background-color": "#f00",        "color": "#fff",        "cursor": "inherit"    
}).text("Open this window again and this message will still be here.");    
return false; 
});

That would bind an event handler to the entire document (so will never get removed until the page unloads), which will react to click events on an element with the id property of click. Ideally you'd use something closer to your dynamic elements in the DOM (perhaps a <div> on your page that is always there and contains all of your page content), since that will improve the efficiency a bit.

Please share on you social sites, if you found it useful.
Thanks
0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment