After running this: $('.bar').css({'color':'#fff'});
hover for .bar stops working. Why?
Also, $('.bar:hover').css({'color':'#fff'});
doesn't change hover's color too, why? What am I missing?
After running this: $('.bar').css({'color':'#fff'});
hover for .bar stops working. Why?
Also, $('.bar:hover').css({'color':'#fff'});
doesn't change hover's color too, why? What am I missing?
You haven't defined what you mean by "hover", but if you're talking about CSS :hover
, then it's because inline styles (as set by .css()
override stylesheet styles.
You can add !important
to your CSS definition to override the inline.
.bar:hover {
color: #ABCDEF !important;
}
I don't believe this works with older IE though.
DEMO: http://jsfiddle.net/hh4NJ/1/
Another (and arguably better) solution would be to use .addClass()
instead of .css()
to change the style. Then you can take care of all of it in your CSS (except for adding/removing the class of course).
$('.bar').addClass('whiteColor');
.whiteColor {
color:#fff;
}
DEMO: http://jsfiddle.net/hh4NJ/2/
Regarding your update, you can't use pseudo selectors like :hover
for DOM selection.
In the cascade, rules in the style attribute will beat rules applied with a selector.
The jQuery css
method modifies the style attribute.
Keep your CSS and JS separate. Use JS to edit add and remove classes from the HTML, and apply your CSS using a class selector. (Make sure that the :hover
rule still has a specific enough selector though).
As a quick and dirty solution, you can also make your :hover
rules !important
, but you shouldn't.
Also,
$('.bar:hover').css({'color':'#fff'});
doesn't change hover's color too, why?
jQuery's selector engine matches elements, it doesn't modify the stylesheet. If this was supported then you would be saying "At the time this code executes, make the .bar I am pointing to white" not "When I point at a .bar, make it white".