How to trigger CSS "hover state" using Javascript? [duplicate]
CSS's "hovered state" will trigger when the user hovers over an element:
<style>
.element{
}
.element:hover{
background-color:red;
}
</style>
How can we set the element to "hovered state" using Javascript?
Is it possible?
You're probably better off duplicating the :hover styles into another class and then just adding that class name to the element when you want them to change permanently. Pseudo-classes are "pseudo" for a reason.
If you could accept using :focus
instead of hover, you can use:
var links = document.getElementsByTagName('a');
links[0].focus();
JS Fiddle demo.
Or
var linkToFocus = document.getElementById('link');
linkToFocus.focus();
JS Fiddle demo.
This approach, obviously, requires adapting your CSS to include the a:focus
style:
a:link, a:visited {
background-color: #fff;
}
a:hover, a:focus, a:active {
background-color: #f00;
}