Javier Ortega
Javier Ortega

Reputation: 157

Detect if Im hovering an element using vanilla javascript

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.

Upvotes: 0

Views: 2976

Answers (1)

Bill Geoghegan
Bill Geoghegan

Reputation: 81

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!');
     }
  }
});

Upvotes: 2

Related Questions