Wasim A.
Wasim A.

Reputation: 9890

Jquery.Hover not working for dynamic Element

Here is my code

$(".inboxfeedlist li").hover(function(e){alert('');}

This is not working for dynamically created elements, even i have use

$(".inboxfeedlist li").bind('hover',function(){})

is also not working, what's problem with code.

Upvotes: 7

Views: 20931

Answers (8)

Khandad Niazi
Khandad Niazi

Reputation: 2396

Here is the use and details of these functions

http://api.jquery.com/live/

$( selector ).live( events, data, handler ); // jQuery 1.3+

$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+

$( document ).on( events, selector, data, handler ); // jQuery 1.7+

Upvotes: 0

eduardomozart
eduardomozart

Reputation: 1454

live become deprecated at jQuery 1.9. We can use on with mouseenter and mouseleave events instead:

$(document).on("mouseenter", ".save-btn", function(e) {
    $(this).css("background-image","url('ie/imgs/btn/hover-btn.png')");
    $(this).find("a").css("background-image","url('ie/imgs/btn/hover-btn-left.png')");
});

$(document).on("mouseleave", ".save-btn", function(e) {
    $(this).css("background-image","url('ie/imgs/btn/btn.png')");
    $(this).find("a").css("background-image","url('ie/imgs/btn/btn-left.png')");
});

For some reason I can't use hover with on. It simply doesn't work. But, from what I have read, hover is just an adaptation from mouseenter and mouseleave, so it is fine. (https://stackoverflow.com/a/4463384/1031340)

If you do not need to support IE6, I recommend you use :hover on your CSS (if it is a change only in CSS, how example above).

Upvotes: 39

Sandeep Pal
Sandeep Pal

Reputation: 2175

You could use something like this:

$(document).on('mouseover','div.cover-wrapper',function(){
    $(this).css({'border':'1px solid #000'});
});


$(document).on('mouseout','div.cover-wrapper',function(){
    $(this).css({'border':'none'});
});

Upvotes: 0

topek
topek

Reputation: 18979

Use the live method:

$(".inboxfeedlist li").live('hover', function(e){alert('');});

A side note hover does take two callback functions, did you mean mouseover

Upvotes: 3

jbabey
jbabey

Reputation: 46647

$('.inboxfeedlist li').live('hover', function(e) { alert(''); });

jQuery live

jQuery delegate

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

Sounds like you need live or delegate. Delegate is prefered

$(document.body).delegate(".inboxfeedlist li", "hover", function(){
        alert('');
});

Upvotes: 1

Sam
Sam

Reputation: 15771

Use delegate or live to bind the events. This will make sure anything added dynamically will be bound to the event handler as well.

Upvotes: 1

swatkins
swatkins

Reputation: 13630

try live

$(".inboxfeedlist li").live('hover',function(){});

Upvotes: 3

Related Questions