Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery hover, mouseenter, and mouseleave not working after .appendTo

Tags:

jquery

I bind the mouseenter and mouseleave event in $document.ready() like this:

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

The user can request more search results which have the class ".collection_add_to". They are appended to the existing search results like this:

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

I doubled checked that the returned results have the class ".collection_add_to". I also tried to rebind this in 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 is not working anymore on the newly added items. When using the $load() function, it works. How can I make the hover-event working again on dynamically loaded content, especially when content is added with append() or appendTo()?

edit

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 from a node which should be higher in the DOM than the target element.

like image 621
user1283043 Avatar asked Jul 28 '12 22:07

user1283043


2 Answers

You should delegate the event, you can use 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"); 
});
like image 166
undefined Avatar answered Nov 04 '22 04:11

undefined


You need to use event delegation eg.

$( 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"); });
like image 42
Musa Avatar answered Nov 04 '22 03:11

Musa