JQuery hover, mouseenter and mouseleave not working after .appendTo

I bind the mouseenter and mouseleave event in $ document.ready () as follows:

$( ".collection_add_to" ).hover( function() { $(this).find( ".playlists" ).fadeIn("fast"); }, function() { $(this).find( ".playlists" ).fadeOut("fast"); } ); 

The user may request additional search results that have the class .collection_add_to. They are added to existing search results as follows:

 $.get("context/collection/", $data, function(result) { $( result ).appendTo( "#collection_song_items" ); // rebind_hover(); }); 

I double-checked that the returned results have a class of ".collection_add_to". I also tried to restore this in an extra routine:

 function rebind_hover() { $( ".collection_add_to" ).hover( function() { $(this).find( ".playlists" ).fadeIn("fast"); }, function() { $(this).find( ".playlists" ).fadeOut("fast"); } ); } 

Nothing worked, the hover event no longer works on newly added elements. When using the $ load () function, it works. How to make the hover event work again with dynamically loaded content, especially when the content is added using append () or appendTo ()?

change

Thanks to sacho on irc and Raminson:

 $(document).on("mouseenter", ".collection_add_to", function() { console.log("MOUSEENTER"); }); $(document).on("mouseleave", ".collection_add_to", function() { console.log("MOUSELEAVE"); }); 

It was not clear to me that event delegation should be done with node, which should be higher in the DOM than the target element.

+7
source share
3 answers

You must delegate the event, you can use the on() method, try the following:

 $(document).on('mouseenter', ".collection_add_to", function() { $(this).find( ".playlists" ).fadeIn("fast"); }).on('mouseleave', ".collection_add_to", function() { $(this).find( ".playlists" ).fadeOut("fast"); }); 
+11
source

You need to use event delegation, for example.

 $( document ).on('hover', ".collection_add_to", function(e){ if (e.type == "mouseover") { $(this).find( ".playlists" ).fadeIn("fast"); } else if (e.type == "mouseout") { $(this).find( ".playlists" ).fadeOut("fast"); } ); 

or

 $( document ).on( "mouseover", ".collection_add_to" , function() { $(this).find( ".playlists" ).fadeIn("fast"); }) .on( "mouseout", ".collection_add_to", function() { $(this).find( ".playlists" ).fadeOut("fast"); }); 
+2
source

jQuery can only act in the original rendered DOM not with a DOM element to be added later.

You can try jQuery.delegate () or jQuery.on () .

0
source

All Articles