Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Hover not working

Tags:

html

jquery

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>

like image 955
user1122925 Avatar asked Mar 11 '13 19:03

user1122925


People also ask

How to use hover using jQuery?

The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element. Syntax: $(selector). hover(Function_in, Function_out);

What is the jQuery equivalent of Onmouseover?

jQuery mouseover() Method The mouseover() method triggers the mouseover event, or attaches a function to run when a mouseover event occurs. Note: Unlike the mouseenter event, the mouseover event triggers if a mouse pointer enters any child elements as well as the selected element.

How will you check if an element is hovered or not using CSS?

How do you know if an element is being hovered in JavaScript? Answer: Use the CSS :hover Pseudo-class You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.

Is not a function error jQuery?

on if not a function" jQuery error occurs for 2 main reasons: Loading an old version of the jQuery library that doesn't support the on function. Loading a library that overrides the value of the dollar sign $ variable.


2 Answers

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

like image 88
wirey00 Avatar answered Sep 21 '22 19:09

wirey00


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");
});
like image 22
Ian Wood Avatar answered Sep 17 '22 19:09

Ian Wood