2

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";
6
  • This has been answered before here. Commented Nov 29, 2014 at 23:17
  • Yes! it didnt work with me either Commented Nov 29, 2014 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? Commented Nov 29, 2014 at 23:19
  • Actually, this question 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. Commented Nov 29, 2014 at 23:20
  • 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. Commented Nov 29, 2014 at 23:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.