Reputation: 1972
I have JQUERY that loads (.load) a piece of code dynamically. It has buttons in it which should respond to the following:
$(":button").on('mouseout mouseover', ETC... );
These newly loaded buttons do not inherit the mouseout mouseover events. How can I fix this? I tried putting a repeat of the code in loaded element, but then I double mouseover mouseout older loaded elements.
Upvotes: 2
Views: 61
Reputation: 4228
For those looking for this answer, the problem is that you can't attach events to an element you haven't created yet (eg. that you load dynamically via ajax).
The simple solution is to listen to the event on a container element. This is a feature of event delegation.
When an event occurs on one of these dynamic elements (such as a click), the event bubbles up through the DOM tree giving each parent the opportunity to listen and react to that event.
Example HTML:
<div id="container"></div>
Example JS:
// Populate container dynamically (could be via AJAX)
$('#container').html('<button class="button">Dynamic Button</button>');
$('#container').on('click', '.button', function() {
// This attaches the listener to a container element.
// When the child '.button' element is clicked the event will bubble up and
// we can handle it here.
});
$(document).on('click', '.button', function() {
// This one is bound at the document level and will also fire unless
// an listener stops the propagation. It would fire last.
});
So which one should you attach your listener to? If you have a container which is persisting then it is more efficient to attach the listener to the container (rather than all the way up the top at the document
) because it can be handled sooner (less bubbling).
Upvotes: 1
Reputation: 13344
$(document).on('mouseout mouseover', ':button', function () { /*...*/ });
Upvotes: 1