Skip to content Skip to sidebar Skip to footer

Bind Events To Dynamically Added Elements

I'm trying to bind functions to newly added elements using jquery...I have tried numerous examples online, but somehow nothing works for me. I created a form with id and a button,

Solution 1:

Got basically two options to do this:

  1. Bind your events after appending the new html:

    $(this).ajaxStop(function(){
         $(this).after($(d).find(".edit-content").html());
         // do you binding here
    });
    
  2. Use event delegation (with .on() or .delegate()).

    $('.some-container').on('click', '.edit-button', function(e) {...});
    

    This will delegate the click event to an element .some-container for any children with class .edit-button, not matter the latter was already in the dom or loaded afterwards.

Solution 2:

To add events to elements which are added to the DOM after page load you need to use either delegate(), or if you're using jQuery 1.7+ on().

$(".edit-content").delegate("#myDiv", "click", function() {
    //do stuff when#myDiv gets clicked.
});

API: DelegateOn

Post a Comment for "Bind Events To Dynamically Added Elements"