I have some elements that are created from an AJAX call. Within those elements, there is a child element that when hovered needs to show another child element that was dynamically created. When I run the .hover
jquery in a fiddle, it works fine. When I implement it in my code, it doesn't want to work.
I was wondering if it depends on when the .hover
script is loaded vs when the elements are loaded from AJAX. Does one need to go before the other? Should a .promise
be enacted to wait for the AJAX elements to load before the .hover
script is run?
Here is a fiddle of my example.
For dynamically generated elements, events should be delegated from one of static parents of the element or document object, you can use on
or delegate
method.
$(document).on({
mouseenter: function() {
$(this).next('.show').fadeIn(800);
},
mouseleave: function() {
$(this).next('.show').delay(800).fadeOut(800);
}
}, '.touch');
I understand your question to mean that you are attaching an event to an element that may not exist yet. Instead of binding to the element (which .hover()
is shorthand for) you should delegate it to a permanent container element. You can do this with either delegate()
or .on()
depending on jQuery version.
Here's what it would look like in your fiddle: http://jsfiddle.net/7dcuh/15/
You should try to insert the script inside the ajax response. like
<script> </script>
or you serve the script when the ajax call is complete or success
jQuery.ajax({
success:function(){jQuery('selector').yourfunction();},
});
if you dont, the script will run and not find the selectors in the dom and the script wont run again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With