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>
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);
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 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.
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.
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
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With