Jquery live hover

I can't seem to convert the following to a live hover

$("li.favorite_item").hover( function () { $(this).append($(" <a href='#' class='button'>x</a>")); }, function () { $(this).find("a:last").remove(); } ); 

I tried:

 $("li.favorite_item"").live('hover', function() { function () { $(this).append($(" <a href='#' class='button'>x</a>")); }, function () { $(this).find("a:last").remove(); } }); 

But that will not work.

+7
source share
3 answers

From jQuery 1.7 + .live () is deprecated , and .delegate () has been replaced by the .on () method.

Use .on () and .off () instead of .live () and. Die (). Use .on () instead of .delegate ().

Converting old code is simple as described here .


You need to call events that .hover() displayed separately, for example:

 $("li.favorite_item").live('mouseenter', function() { $(this).append($(" <a href='#' class='button'>x</a>")); }).live('mouseleave', function () { $(this).find("a:last").remove(); }); 

.hover() not an event function, for example .click() , it is just a special shortcut for .mouseenter(handler1).mouseleave(handler2) ... so you need to do the same in the .live() call.

If you are using jQuery 1.4.3+, you can use a map to simplify it, for example:

 $("li.favorite_item").live({ mouseenter: function() { $(this).append($(" <a href='#' class='button'>x</a>")); }, mouseleave: function () { $(this).find("a:last").remove(); } }); 

Also, if indicated on a specific <ul> , .delegate() is a better option, for example:

 $("#myUL").delegate("li.favorite_item", { mouseenter: function() { $(this).append($(" <a href='#' class='button'>x</a>")); }, mouseleave: function () { $(this).find("a:last").remove(); } }); 
+29
source

The .live () syntax was nicer, but now we have to use .on ().

You can use the event map in the document, and the selector as the second argument:

 $(document).on({ mouseenter: function () { $(this).append("<a href='#' class='button'>x</a>"); }, mouseleave: function () { $(this).find("a:last").remove(); } }, "li.favourite_item"); 
+5
source

It's right...

 $("#your_div_id").live('mouseover',function(){ $(this).find(".child_div").css('background-color','#111111'); }).live('mouseout',function(){ $(this).find(".child_div").css('background-color','#757575'); }); 
-one
source

All Articles