Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pure javascript to check if something has hover (without setting on mouseover/out)

I have seen this jQuery syntax:

if($(element).is(':hover')) { do something} 

Since I am not using jQuery, I am looking for the best way to do this in pure javascript.

I know I could keep a global variable and set/unset it using mouseover and mouseout, but I'm wondering if there is some way to inspect the element's native properties via the DOM instead? Maybe something like this:

if(element.style.className.hovered === true) {do something} 

Also, it must be cross browser compatible.

like image 674
mulllhausen Avatar asked Feb 10 '13 05:02

mulllhausen


People also ask

How do you check if an element is hovered or not using CSS?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery. The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.

Is there hover in javascript?

jQuery hover() Method The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events.


2 Answers

Simply using element.matches(':hover') seems to work well for me, you can use a comprehensive polyfill for older browsers too: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

like image 58
Hugheth Avatar answered Oct 08 '22 13:10

Hugheth


You can use querySelector for IE>=8:

const isHover = e => e.parentElement.querySelector(':hover') === e;        const myDiv = document.getElementById('mydiv');  document.addEventListener('mousemove', function checkHover() {    const hovered = isHover(myDiv);    if (hovered !== checkHover.hovered) {      console.log(hovered ? 'hovered' : 'not hovered');      checkHover.hovered = hovered;    }  });
.whyToCheckMe {position: absolute;left: 100px;top: 50px;}
<div id="mydiv">HoverMe    <div class="whyToCheckMe">Do I need to be checked too?</div>  </div>

to fallback I think it is ok @Kolink answer.

like image 23
zb' Avatar answered Oct 08 '22 13:10

zb'