简体   繁体   中英

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?

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")

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> 

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM