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>

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
user1122925
  • 237
  • 2
  • 4
  • 12

2 Answers2

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

wirey00
  • 33,517
  • 7
  • 54
  • 65
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");
});
Ian Wood
  • 6,515
  • 5
  • 34
  • 73