How to bind Events on Ajax loaded Content?
Solution 1
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink
instead of data
- http://jsfiddle.net/EFjzG/
Solution 2
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element
in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
Solution 3
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
Solution 4
As of jQuery 1.7, the .live()
method is deprecated. Use .on()
to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
Solution 5
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
Related videos on Youtube
confile
Java, GWT, JavaScript, Grails, Groovy, Swift, Objective-C, iOS
Updated on May 22, 2021Comments
-
confile about 3 years
I have a link,
myLink
, that should insert AJAX-loaded content into adiv
(appendedContainer) of my HTML page. The problem is that theclick
event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. Theclick
event is bound on DOM elements that are not loaded with my AJAX function.What do I have to change, such that the event will be bound?
My HTML:
<a class="LoadFromAjax" href="someurl">Load Ajax</a> <div class="appendedContainer"></div>
My JavaScript:
$(".LoadFromAjax").on("click", function(event) { event.preventDefault(); var url = $(this).attr("href"), appendedContainer = $(".appendedContainer"); $.ajax({ url: url, type : 'get', complete : function( qXHR, textStatus ) { if (textStatus === 'success') { var data = qXHR.responseText appendedContainer.hide(); appendedContainer.append(data); appendedContainer.fadeIn(); } } }); }); $(".mylink").on("click", function(event) { alert("new link clicked!");});
The content to be loaded:
<div>some content</div> <a class="mylink" href="otherurl">Link</a>
-
Ram about 11 yearsNote: The following is not working. You are missing
.
for the class selector. -
confile about 11 yearsThis was a typo! It is still not working.
-
km6zla about 11 yearsSee jquery .load() method. $('#target').load('source.html');
-
confile about 11 yearsDoes load() do something different?
-
Fefar Ravi about 2 yearsMay be this can more helpful.
-
-
confile about 11 yearsThis is what I wrote that I did.
-
dsgriffin about 11 years@confile Really? I've read your question twice and don't see it either in writing or in code?
-
Adil Shaikh about 11 years@confile.. See the answer agian .. that's different from what you have
-
Adil Shaikh about 11 years
.live()
is deprecated and removed in latest jquery version. -
confile about 11 years@Zenith I added a Not to my question at the bottom. What you wrote is also not working for me.
-
dsgriffin about 11 years@confile My answer does work!! here's an example of it - jsfiddle.net/EFjzG
-
Win Maw Oo over 9 yearsHi, this answer is working just fine. Event is attached on whole document, so basically every click on page is triggering event, but then, selector '.mylink' is applied to filter click events we need. Excellent technique.
-
Admin over 9 yearsWhere does this "Sys.Application" comes from? --'
-
Michael over 9 yearsIt appears to belong to ASP.NET: msdn.microsoft.com/en-us/library/vstudio/…
-
Admin almost 8 years@d.g this answer is good.but how Can I do this in pure js without jquery?
-
R. Schreurs almost 6 yearsI prefer this answer to the one by @lifetimes, because it tells me to set the handler to some parent element that is present at load time, not necessarily all the way up to document. This makes the selector in the second argument to
on
less prone to unintended matches. -
Paulo Henrique over 5 yearsThe answer is correct (just wanted to enforce it). $(".mylink").on("click", function(event) { alert("new link clicked!");}); is not the same as $(document).on("click", '.mylink', function(event) { alert("new link clicked!"); });
-
jafar pinjar over 4 yearsIf the ajax loaded html class also parent-element then its not working
-
drupalfan almost 2 yearsThank you, this solution helped me to solve the problem at ajax loaded webform ... What is the reason for this problem?