Check if the mouse is inside the div

I want to use an if statement to check if the mouse is inside a specific div, something like this:

if ( mouse is inside #element ) { // do something } else { return; } 

This will cause the function to start when the mouse is inside #element, and stop when the mouse is outside #element.

+5
source share
3 answers

you can register jQuery handlers:

 var isOnDiv = false; $(yourDiv).mouseenter(function(){isOnDiv=true;}); $(yourDiv).mouseleave(function(){isOnDiv=false;}); 

no jQuery alternative:

 document.getElementById("element").addEventListener("mouseenter", function( ) {isOnDiv=true;}); document.getElementById("element").addEventListener("mouseout", function( ) {isOnDiv=false;}); 

and somewhere:

 if ( isOnDiv===true ) { // do something } else { return; } 
+7
source

Well, what kind of events. Just attach an event listener to the div you want to control.

 var div = document.getElementById('myDiv'); div.addEventListener('mouseenter', function(){ // stuff to do when the mouse enters this div }, false); 

If you want to do this using math, you still need to have an event on the parent element or something else to get the coordinates of the mouse, which will then be stored in the event object that is passed to Chime.

 var body = document.getElementsByTagName('body'); var divRect = document.getElementById('myDiv').getBoundingClientRect(); body.addEventListener('mousemove', function(event){ if (event.clientX >= divRect.left && event.clientX <= divRect.right && event.clientY >= divRect.top && event.clientY <= divRect.bottom) { // Mouse is inside element. } }, false); 

But it is best to use the above method.

+4
source
 $("div").mouseover(function(){ //here your stuff so simple.. }); 

You can do something like this

 var flag = false; $("div").mouseover(function(){ flag = true; testing(); }); $("div").mouseout(function(){ flag = false; testing(); }); function testing(){ if(flag){ //mouse hover }else{ //mouse out } } 
0
source

Source: https://habr.com/ru/post/1247604/


All Articles