I've been trying to find code to simulate mouseover
in Chrome but even though the "mouseover" listener gets fired, the CSS "hover" declaration is never set!
I tried also doing:
//Called within mouseover listener
theElement.classList.add("hover");
But nothing seems to change the element to what is declared in its hover
declaration.
Is this possible?
You can use pseudo:styler, a library which can apply CSS pseudo-classes to elements.
Disclaimer: I am a coauthor of this library. We designed it to additionally support cross-origin stylesheets, specifically for use in Chrome extensions where you likely lack control over the CSS rules of the page.
Background
I stumbled upon this question while trying to write automated tests, to verify, that a certain set of elements on a given page all receive have the some set of css properties set by the css for on hover events.
While the above answer perfectly explains, why it is not possible to simply trigger the hover event by JS and then take a prove of some css value of interest, it does answer the initial question "How do I simulate a mouseover in pure JavaScript that activates the CSS “:hover”?" only partly.
Disclaimer
This is not a performant solution. We use it only for automated testing, where performance is not a concern.
Solution
Explanation
generateEvent reads all css files, , replaces :hover with an empty string and applies it. This has the effect, that all :hover styles are applied. Now one can probe for a howered style and set back to initial state by stopping the Simulation.
Why do we apply the hover effect for the whole document and not just for the element of interest by getting the from the sheets and then perform a element.css(...)?
Done as that, the style would be applied inline, this would override other styles, which might not be overriden by the original css hover-style.
How would I now simulate the hover for a single element?
This is not performant, so better don't. If you must, you could check with the element.is(selectorOfInterest) if the style applies for your element and only use those styles.
Example
In Jasmine you can e.g. now perform:
You can simulate the mouseover event like this:
HTML
JavaScript
You can't. It's not a trusted event.
You have to add a class and add/remove that on the mouseover/mouseout events manually.
What I usually do in this case is adding a class using javascript.. and attaching the same
CSS
as the:hover
to this classTry using
Or for older browsers:
you will ofcourse have to use
onmouseout
to remove the "hovered" class when you leave the element...