How can I check whether the cursor is over a div
on the html page with JQuery/Javascript?
I'm trying to get cursor coordinates to see if they are in the rectangle of my element. Maybe there are predefined methods?
UPD, don't say anything about hover
events, etc. I need some method which will return true/false for some element at the page, like:
var result = underElement('#someDiv'); // true/false
I'm not really sure why you wish to avoid hover so badly: consider the following script
$(function(){
$('*').hover(function(){
$(this).data('hover',1); //store in that element that the mouse is over it
},
function(){
$(this).data('hover',0); //store in that element that the mouse is no longer over it
});
window.isHovering = function (selector) {
return $(selector).data('hover')?true:false; //check element for hover property
}
});
Basically the idea is that you use hover to set a flag on the element that the mouse is over it/no longer over it. And then you write a function that checks for that flag.
For the sake of completeness I will add a couple of changes that I believe will help a bit for performance.
Use delegation to bind the event to one element, instead of binding it to all existent elements.
$(document).on({
mouseenter: function(evt) {
$(evt.target).data('hovering', true);
},
mouseleave: function(evt) {
$(evt.target).data('hovering', false);
}
}, "*");
Add a jQuery pseudo-expression :hovering
.
jQuery.expr[":"].hovering = function(elem) {
return $(elem).data('hovering') ? true : false;
};
Usage:
var isHovering = $('#someDiv').is(":hovering");
The simplest way would probably be to just track which element the mouse is over at all times. Try something like:
<div id="1" style="border:solid 1px red; width:50px; height:50px;"></div>
<div id="2" style="border:solid 1px blue; width:50px; height:50px;"></div>
<div id="3" style="border:solid 1px green; width:50px; height:50px;"></div>
<input type="hidden" id="mouseTracker" />
$(document).ready(function() {
$('*').hover(function() {
$('#mouseTracker').val(this.id);
});
});
and then your function is simply
function mouseIsOverElement(elemId) {
return elemId === $('#mouseTracker').val();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With