1

I need to tweak a script and hard-write hover to make it visible. How can I do that using javascript.

I tried so far several ways, but it didn't work out.

  document.getElementById("tooltip").className += ":hover";
user3378649
  • 5,154
  • 14
  • 52
  • 76
  • This has been answered before [here](http://stackoverflow.com/questions/2228376/trigger-onmouseover-event-programatically-in-javascript). – JCOC611 Nov 29 '14 at 23:17
  • Yes! it didnt work with me either – user3378649 Nov 29 '14 at 23:18
  • 7
    What are you trying to do? Style an element when the mouse is over it (with JavaScript), or write a CSS rule for the `:hover` state of the element (so the hover-effect is applied with CSS)? Or use JavaScript to force the element into its `:hover` state? – David Thomas Nov 29 '14 at 23:19
  • Actually, [this question](http://stackoverflow.com/questions/10680446/trigger-the-csshover-event-with-js) should be of more help than the other one I posted. TL;DR of it is: create an alternative class that has the same style as the `:hover` and then add that class to your element. – JCOC611 Nov 29 '14 at 23:20
  • @DavidThomas I wanna use JavaScript to force the element into its :hover state? – user3378649 Nov 29 '14 at 23:25
  • 3
    You can't trigger the *hover* state of an element in JavaScript. You will have to add a normal class with the same CSS as your `:hover`, then add that class to your element. – Spencer Wieczorek Nov 29 '14 at 23:42

1 Answers1

1

One way to do what I believe is what you're trying to achieve, is to toggle a "hover" CSS class.

var tooltip = document.getElementById('tooltip');
var toggle = document.getElementById('toggle');
var isHover = false;

toggle.onclick = function() {
    if (!isHover) {
        tooltip.classList.add('hover');
    } else {
        tooltip.classList.remove('hover');
    }
    isHover = !isHover;
};
#tooltip {
    width: 200px;
    height: 200px;
    background: blue;
}
#tooltip:hover,
#tooltip.hover {
    background: red;
}
<div id="tooltip"></div>
<button id="toggle">toggle hover</button>

You cannot modify a pseudo class (ex :hover) using JavaScript.

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64