Surajit Mitra
Surajit Mitra

Reputation: 414

Javascript to see that div on hover or not

I am trying to write a pure javascript to know that a particular div is on hover or not, if hover then variable = true else false.

$("#demo").hover(function(){
$(this).css("background-color", "yellow");
}, function(){
$(this).css("background-color", "black");
});

I tried searching in web, but I am getting only solutions based on jquery. But I want it on javascript.

<div id="demo">Hover on me</div>

Can anybody help me on this to write JavaScript same as above jquery?

Upvotes: 0

Views: 106

Answers (3)

CertainPerformance
CertainPerformance

Reputation: 370929

Add event listeners to mouseover and mouseout, both of which reassign a boolean:

let isHovered = false;
const demo = document.querySelector('#demo');
demo.addEventListener('mouseover', () => isHovered = true);
demo.addEventListener('mouseout', () => isHovered = false);
setInterval(() => console.log(isHovered), 200);
<div id="demo">Hover on me</div>

Or, if you wanted to exactly imitate the code you posted in your question, just add a :hover to your CSS rules, no Javascript required:

#demo {
  background-color: black;
}
#demo:hover {
  background-color: yellow;
}
<div id="demo">Hover on me</div>

Upvotes: 0

Brooke Holmes
Brooke Holmes

Reputation: 1622

The jQuery .hover() method binds two functions that are called for the mouseover and mouseout events.

If you add event listeners to those events you can replicate the behaviour.

function hover(el, hoverOnCb, hoverOffCb) {
  el.addEventListener("mouseover", hoverOnCb);
  el.addEventListener("mouseout", hoverOffCb);
}

var demoElement = document.getElementById("demo");

hover(demoElement, function() {
  this.style.backgroundColor = "yellow";
}, function() {
  this.style.backgroundColor = "black";
});
<div id="demo">Hover me!</div>

  • this works the same as jQuery's $(this)
  • this.style.backgroundColor = "black" does the same as $(this).css("background-color", "black")

Upvotes: 2

Imran
Imran

Reputation: 530

var div = document.getElementById('demo');

div.addEventListener('mouseenter', function(){
  this.style.background = 'red';
});

div.addEventListener('mouseleave', function(){
  this.style.background = 'green';
});

Upvotes: 0

Related Questions