views:

40

answers:

2

Hello, how can I check whether the cursor is over some div at the html page with JQuery/Javascript?

I'm trying to get cursor coordinates and look 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
+1  A: 

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.

Ramuns Usovs
+1 I like this solution a lot. Don't you just need `return $(selector).data('hover');` at the end though?
fearofawhackplanet
+1  A: 

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();
}
fearofawhackplanet