Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the css :hover state in a jQuery selector?

I need to define a div's background color on :hover with jQuery, but the following doesn't seem to work:

$(".myclass:hover div").css("background-color","red"); 

How can I get the same result? It's important that it has to be done with jQuery but for some reason it doesn't work. Any suggestions? Thanks!

like image 596
ErikTailor Avatar asked Jan 10 '14 18:01

ErikTailor


People also ask

Is hover a CSS selector?

The :hover selector is used to select elements when you mouse over them. Tip: The :hover selector can be used on all elements, not only on links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :active selector to style the active link.

Does jQuery handle hover?

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.


1 Answers

I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this

$("div.myclass").hover(function() {   $(this).css("background-color","red") }); 

You can change your selector as per your need.

As commented by @A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this

$(".myclass, .myclass2").hover(function(e) {      $(this).css("background-color",e.type === "mouseenter"?"red":"transparent")  }) 

Js Fiddle Demo

like image 168
Sachin Avatar answered Sep 26 '22 14:09

Sachin