Can I disable a CSS :hover effect via JavaScript?
You can manipulate the stylesheets and stylesheet rules themselves with javascript
var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);
Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.
There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover
state itself.
You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.
HTML
<body class="nojQuery">
CSS
/* Limit the hover styles in your CSS so that they only apply when the nojQuery
class is present */
body.nojQuery ul#mainFilter a:hover {
/* CSS-only hover styles go here */
}
JavaScript
// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.
$(function(){}
$('body').removeClass('nojQuery');
)
Use a second class that has only the hover assigned:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
Now you can use Jquery to remove the class, for instance if the element has been clicked:
JQUERY
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
Hope this answer is helpful.