53

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?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • Seems like you taking a hammer to stick what apears to be not a nail. What are you trying to do exactly? – the_drow Jun 20 '11 at 05:02
  • like when do you want to trigger it?? – Balanivash Jun 20 '11 at 05:02
  • 1
    @Balanivash: nevermind that. Why does he want to trigger hover on it's own? Why shouldn't he copy-paste the style and use element.className = 'newClass'? – the_drow Jun 20 '11 at 05:04
  • 4
    Here's my use case: I'm mirroring a page over WebSockets using DOM Mutation Observers. `:hover` state is not in the DOM so need some other generic way to handle it. – Tamlyn Mar 13 '15 at 12:02
  • @the_drow, Have a trip to http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java#comment-11386801 – Pacerier Mar 13 '15 at 15:28
  • @Balanivash, I want to trigger it using Javascript on a certain event unrelated to user's input. This can be a timing event or something else altogether. – Pacerier Mar 13 '15 at 15:28
  • @Pacerier: think you can do this use jQuery like `$().trigger('mouseenter');` – Balanivash Mar 13 '15 at 19:06
  • @Balanivash, I only use Vanilla-JS, no jquery. – Pacerier Mar 14 '15 at 08:49
  • Please check this [http://stackoverflow.com/questions/17226676/how-do-i-simulate-a-mouseover-in-pure-javascript-that-activates-the-css-hover] – Balanivash Mar 14 '15 at 09:03
  • @the_drow I’m writing unit tests for CSS using https://github.com/studio-b12/tape-css. I’m facing exactly the same problem. – tomekwi Oct 13 '15 at 09:14

2 Answers2

32

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;
}
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 2
    But why would one do such a thing? – the_drow Jun 20 '11 at 05:09
  • 2
    @the_drow: I have absolutely no idea; but I'd suspect that it's to show/highlight something on page-load, maybe? There are better ways of doing that, of course, but without further information I can only try to answer the question that was asked. Irrespective of the use-case, sadly. – David Thomas Jun 20 '11 at 05:10
  • 8
    Good answer, but the question asked how to trigger ":hover", not ":focus". – CITguy Jan 06 '20 at 19:22
  • 2
    @the_drow: This could be useful when creating a components-demo-page, where you want to show the different button styles in their different states (neutral, disabled, hovered, focused, active). – Jan Aagaard Feb 23 '21 at 09:39
  • 1
    @the_drow This could be used for example when you want to quickly automate minor tasks via the DevTools wherein additional elements are only revealed/added to DOM when hovered. – Melvin Abraham Apr 03 '21 at 06:26
  • Im here looking for this solution myself. A client needs an ability to wrap many Shortcodes in a Drupal CMS with the ability of a parent element to take the link from a deeper child anchor and activate it, but to show the hover state of the anchor. unfortunately there are no classes for the hover effect it's all :hover and all old code. Normally its a case of wrap the whole thing with an anchor with a fake button inside but the old site structure dictates otherwise :-P – Pocketninja May 26 '21 at 17:55
30

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.

Scott
  • 2,753
  • 1
  • 24
  • 31
  • This is what I'm doing right now and am looking for better alternatives. – Pacerier Mar 13 '15 at 15:29
  • I'm not sure what definition of "better" you're looking for. Dynamically triggering a class through JavaScript should use a proper class and not a pseud-class. The entire purpose for `:hover` is to *only* be used when a user hovers over an element. This is expressly why JavaScript methods like the Element.classList (https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) collection exist. – Scott Mar 13 '15 at 16:43
  • That's solving the problem the wrong way. The problem is I need to activate `:hover` and the straightforward solution would be a command to do **exactly that**. – Pacerier Mar 13 '15 at 17:50
  • Without explicitly instructing a user to mouse over a DOM element *you can't* trigger :hover. See the accepted answer here for a technical explanation as to why. http://stackoverflow.com/questions/17226676/how-do-i-simulate-a-mouseover-in-pure-javascript-that-activates-the-css-hover] – Scott Mar 16 '15 at 07:27
  • @Pacerier did you find a solution that worked for you? Curious to know how you solved this. – Scott Mar 18 '15 at 09:08
  • I used a function that applies the style to the element. Needs extra work, but I'll not pollute the global namespace. – Pacerier Mar 19 '15 at 14:46
  • 4
    That doesn't explain it. It begs the question **Why** is hover not a trusted event? – Pacerier Mar 19 '15 at 14:47
  • 6
    Not being a member of the W3C I can only hazard a guess, but this article (http://www.smashingmagazine.com/2013/11/12/an-introduction-to-dom-events/) on Smashing Magazine sheds a little light: _An event is said to be “trusted” when it originates from the device itself, not synthesized from within JavaScript._ You're trying to simulate a hover event rather than it being triggered naturally. Of course you can simulate click events without actually tapping on a mouse button easily enough so it's not a hard standard obviously. Browsers are more forgiving with click but not with hover, apparently. – Scott Mar 20 '15 at 09:26
  • 5
    Exactly, it seems totally arbitrary that we are allowed to call "focus" but not "hover". – Pacerier Mar 23 '15 at 08:15
  • I would assume that hover (and combined with click or mouse up & down for drag & drop), could behave or appear like hijacking a user's system (if you ignore automation cases), so it is not ideal to support. Click I can't say, but focus would allow auto-focus to a target form field or element the site designer wants the user to focus on say for example a text field with missing or incorrect data (e.g. form field validation checks). But that's just my assumptions. – David Apr 07 '15 at 21:00
  • @Pacerier in my case, I need to traverse a list of li using arrow keys and have the same css as it would have if it would hover. So I end up using focus from my JS instead of handling the hover event, which wouldn't be triggered in the scenario of keyboard traversal. – Prashanth Subramanian Apr 05 '18 at 22:34