user1122925
user1122925

Reputation: 237

jQuery - Hover not working

Having a little trouble with .hover()

I'm grabbing some dribbble shots, which are pulled in on page load. And for some reason adding a class via hover doesn't want to work on them.

Although it works perfectly fine with a standard list.

jsFiddle here

JS:

$("#dribbble li").hover(

function () {
    $(this).addClass("hover");
},

function () {
    $(this).removeClass("hover");
});

HTML

<div id="dribbble">
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

Upvotes: 8

Views: 17947

Answers (2)

wirey00
wirey00

Reputation: 33661

Use delegation - I'm guessing your elements aren't getting bound because it's they aren't available in the dom at the time of binding

$("#dribbble").on({
    mouseenter: function () {
       $(this).addClass("hover");
    },
    mouseleave:function () {
       $(this).removeClass("hover");
    }
},'li');

Also you'll have to be more specific with your css if you want it to take precedence over the other styles

#dribbble li.hover {
    background-color:aqua;
}

FIDDLE

Upvotes: 13

Ian Wood
Ian Wood

Reputation: 6573

You need to attach event handlers to elements that exist already. As you are creating li elements you must bind to a parent and then filter to the element you require (which is actually desirable when done correctly).

Try:

$("#dribbble").on('mouseenter','li',function () {
    $(this).addClass("hover");
});

$("#dribbble").on('mouseleave','li',function () {
    $(this).removeClass("hover");
});

Upvotes: 6

Related Questions