Skip to content Skip to sidebar Skip to footer

Check If Mouse Is Inside Div

I want to use an if statement to check if the mouse is inside a certain div, something like this: if ( mouse is inside #element ) { // do something } else { return; } This will

Solution 1:

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 somewhereelse:

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

Solution 2:

Well, that's kinda of what events are for. Simply attach an event listener to the div you want to monitor.

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

If you want to do it using math, you still need to have an event on a parent element or something, to be able to get the mouse coordinates, which will then be stored in an event object, which is passed to the callback.

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's best to use the above method.


Solution 3:

simply you can use this:

var element = document.getElementById("myId");
if (element.parentNode.querySelector(":hover") == element) {
    //Mouse is inside element
} else {
    //Mouse is outside element
}

Improving using the comments

const element = document.getElementById("myId");
if (element.parentNode.matches(":hover")) {
    //Mouse is inside element
} else {
    //Mouse is outside element
}

Solution 4:

$("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
    }
}

Post a Comment for "Check If Mouse Is Inside Div"