I'm having a bit of trouble with the jQuery css()
function at the moment. It is changing the css value of the anchor element's border-top-color
instead of just the anchor element's border-top-color
when hovered. Below is my code.
$("#header #headerlist li a:hover").css("border-top-color","rgb(225, 149, 79)");
Why does it change the #header #headerlist li a
border-top-color and the #header #headerlist li a:hover
properties rather than just the #header #headerlist li a:hover
property?
The reason it doesn't work is because the
:hover
bit doesn't actually give the selector any information about an element.a:hover
in CSS matches on the same exact elements asa
, it's just defining a different set of properties for when the user is hovering over those elements.The jQuery selector is designed to find (select) elements, not to style them.
The
css()
method simply sets an inline style on the elements that are selected, it does not add or change any actual CSS declarations.As other have mentioned, you can use the
hover()
event to get the same behavior. Although, adding a class on the fly is probably better, as another answerer described.However, if you don't need to make it change on-the-fly, I recommend using plain old CSS since it is faster and does not require a user to have javascript enabled.
The reason your example doesn't work is because the selector has no way of detecting :hover since that's a pure CSS thing. Instead you might try using the actual jquery hover method:
Alternatively, you could also use the addclass method as well:
This could be further simplified to:
This code is broken since 1.9
use this instead
add !important to the hover css to avoid the style is overrided. for example:
I don't know exactly why, but this type of changes are better done in CSS, so I'd suggest that, if you really need to change this through JS, create a CSS class, then change that in JS.
CSS
JS
That way you can better separate functionality from presentation.