0

I need to detect if I'm hovering an element using only vanilla javascript. I'm trying this:

    this.element.addEventListener('mousemove', function () {

    var result = this.element.matches(':hover');

    if ( result ) {

      this.element.style.backgroundColor = "yellow";

    }

    console.log(result)

  }.bind( this )) 

But it isn't working as expected due it always console logs "false".

The use case is: A element have a class, and if I hover it, the class is removed and another class is added.

I know that jQuery has it's "hover" function but I need to accomplish that using only vanilla javascript.

Javier Ortega
  • 147
  • 10
  • Does this answer your question? [pure javascript to check if something has hover (without setting on mouseover/out)](https://stackoverflow.com/questions/14795099/pure-javascript-to-check-if-something-has-hover-without-setting-on-mouseover-ou) – spjy Apr 02 '20 at 08:48

1 Answers1

1

With vanilla JS, you can use the onmouseover tag.

<div onmouseover="myFunc(this)">hover me!</div>
function myFunc(el) {
  console.log('hovering element',el);
}

Read more here: https://www.w3schools.com/jsref/event_onmouseover.asp

However, if you have many elements that you want to programmatically add this to, then you can use a class selector in order to do so.

<div class="example">hover me!</div>
<div class="example">Also hover me!</div>
document.addEventListener("DOMContentLoaded", function(){
  // Handler when the DOM is fully loaded 
  var allMyHoverElements = document.getElementsByClassName("example");

  for (var i = 0; i < allMyHoverElements.length; i++) {
     allMyHoverElements.item(i).onmouseover = function() {
       console.log('Hello!');
     }
  }
});