Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 result in the function to start when the mouse is inside #element, and stops when the mouse is outside #element.

like image 295
Maarten Wolfsen Avatar asked Apr 21 '16 10:04

Maarten Wolfsen


People also ask

How can I tell if my cursor is inside a div?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery. The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.

How do you check if the mouse is over an element Javascript?

Use document. elementFromPoint(x, y) method to get the element content on that position when mouse pointer moves over.

How do you know if an element is hovered CSS?

it occurred to me that one way to check if an element is being hovered over is to set an unused property in css :hover and then check if that property exists in javascript.

Is mouse over jQuery?

jQuery | mouseover() with ExamplesThe mouseover() method is an inbuilt method in jQuery which works when mouse pointer moves over the selected elements. Parameters: This method accepts single parameter function which is optional.


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

if ( isOnDiv===true ) {
 // do something
} else {
 return;
}
like image 123
or hor Avatar answered Sep 19 '22 06:09

or hor