Skip to content Skip to sidebar Skip to footer

Newly Appended Objects Don't Respond To Jquery Events From Page Load

I am using Backbone here, but I've also experienced this issue with non-Backbone sites as well. Essentially, my issue is that I define in one javascript file, base.js, a number of

Solution 1:

Why this is?

Because when the event binding code is executed, elements that do not exist in the DOM already will not be affected (how could they be? They don't exist yet!) The "normal" event binding methods (e.g. .click() or .change()) will attach a copy of the event handler function to every element in the matched set.

I can force a new appended element to work with/listen to current events already declared?

You can indeed, by delegating the event handler higher up the DOM tree. Since most DOM events bubble up the tree from the element on which they originate, this works well. With jQuery, you can use the .on() (jQuery 1.7+ - for older versions use .delegate() instead) method to do this:

$("#someCommonAncestor").on("someEvent", ".element", function () {
    // Do stuff
});

The element on which you call .on() must exist in the DOM at the time the code runs. When the event bubbles up far enough to reach whatever #someCommonAncestor may be, jQuery will check to see if the target element matched the selector you passed to .on(). If it does, it will execute the event handler. If it doesn't, the event will continue bubbling to the root of the document and not trigger any handler.

Post a Comment for "Newly Appended Objects Don't Respond To Jquery Events From Page Load"