Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .hover not working on AJAX rendered elements

Tags:

jquery

ajax

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.

like image 436
Plummer Avatar asked Dec 27 '12 14:12

Plummer


3 Answers

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');
like image 128
undefined Avatar answered Sep 28 '22 16:09

undefined


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/

like image 35
Stuart Burrows Avatar answered Sep 28 '22 15:09

Stuart Burrows


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

like image 35
john Smith Avatar answered Sep 28 '22 15:09

john Smith