How to bind Events on Ajax loaded Content?

149,163

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);
}

});
Share:
149,163

Related videos on Youtube

confile
Author by

confile

Java, GWT, JavaScript, Grails, Groovy, Swift, Objective-C, iOS

Updated on May 22, 2021

Comments

  • confile
    confile about 3 years

    I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click 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
      Ram about 11 years
      Note: The following is not working. You are missing . for the class selector.
    • confile
      confile about 11 years
      This was a typo! It is still not working.
    • km6zla
      km6zla about 11 years
      See jquery .load() method. $('#target').load('source.html');
    • confile
      confile about 11 years
      Does load() do something different?
    • Fefar Ravi
      Fefar Ravi about 2 years
      May be this can more helpful.
  • confile
    confile about 11 years
    This is what I wrote that I did.
  • dsgriffin
    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
    Adil Shaikh about 11 years
    @confile.. See the answer agian .. that's different from what you have
  • Adil Shaikh
    Adil Shaikh about 11 years
    .live() is deprecated and removed in latest jquery version.
  • confile
    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
    dsgriffin about 11 years
    @confile My answer does work!! here's an example of it - jsfiddle.net/EFjzG
  • Win Maw Oo
    Win Maw Oo over 9 years
    Hi, 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
    Admin over 9 years
    Where does this "Sys.Application" comes from? --'
  • Michael
    Michael over 9 years
    It appears to belong to ASP.NET: msdn.microsoft.com/en-us/library/vstudio/…
  • Admin
    Admin almost 8 years
    @d.g this answer is good.but how Can I do this in pure js without jquery?
  • R. Schreurs
    R. Schreurs almost 6 years
    I 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
    Paulo Henrique over 5 years
    The 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
    jafar pinjar over 4 years
    If the ajax loaded html class also parent-element then its not working
  • drupalfan
    drupalfan almost 2 years
    Thank you, this solution helped me to solve the problem at ajax loaded webform ... What is the reason for this problem?