Reputation:
I have a CSS-class with a hover pseudo class:
.nav-collapse a:hover {
background: #DEDEDE;
border-radius: 3px;
}
I would like to dynamically change the background color with jQuery, i.e. access the CSS-class (.nav-collapse a:hover) and change the background color. I tried the following, which does not work:
$(".nav-collapse a:hover").css({
"background": "#000",
"color": "#fff",
});
What is the proper way to access the :hover class of a CSS-class?
Upvotes: 2
Views: 2456
Reputation: 723558
If you're simply asking how to modify an existing CSS rule that contains a dynamic pseudo-class, that is not possible by DOM interfacing with jQuery since jQuery deals with DOM elements, not CSS rules — you will need to modify the document stylesheet directly instead, which is often cumbersome. This applies to almost any dynamic pseudo-class, and not just :hover
.
A much more elegant approach is to move the new style declarations to a separate CSS rule with a different class name for example, and apply that class to your element as desired. This decouples your style declarations from your script, eliminating the need to modify your styles from your script altogether. To wit:
.nav-collapse a:hover {
background: #DEDEDE;
border-radius: 3px;
}
.nav-collapse a.scrolling:hover {
background: #000;
color: #fff;
}
And:
$('.nav-collapse a').addClass('scrolling');
Upvotes: 5
Reputation: 18995
This is how:
$(".nav-collapse > a").mouseover(function(){
$(this).css({
"background": "#000",
"color": "#fff",
});
})
$(".nav-collapse > a").mouseout(function(){
$(this).css({
"background": "",
"color": "",
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-collapse">
<a href="#">link</a>
</div>
Upvotes: 2