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

mulllhausen picture mulllhausen · Feb 10, 2013 · Viewed 59.4k times · Source

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.

Answer

zb' picture zb' · Feb 10, 2013

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.