8

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>

2
  • 2
    What do you expect to see? Where is your CSS? Mar 11, 2013 at 19:29
  • Your hover events is workin pretty well. It is not visible due to the jribbble plugin. Perhaps because they ar using some kind of e.stopPropagation() code
    – sdespont
    Mar 11, 2013 at 19:45

2 Answers 2

13

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

6

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");
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.