Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the cursor is over an element? [duplicate]

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
like image 623
Max Frai Avatar asked Aug 03 '10 09:08

Max Frai


3 Answers

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.

like image 189
Ramuns Usovs Avatar answered Oct 14 '22 00:10

Ramuns Usovs


For the sake of completeness I will add a couple of changes that I believe will help a bit for performance.

  1. 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);
      }
    }, "*");
    
  2. Add a jQuery pseudo-expression :hovering.

    jQuery.expr[":"].hovering = function(elem) {
      return $(elem).data('hovering') ? true : false; 
    };
    

Usage:

var isHovering = $('#someDiv').is(":hovering");
like image 21
Alexander Avatar answered Oct 14 '22 01:10

Alexander


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();
}
like image 42
fearofawhackplanet Avatar answered Oct 14 '22 02:10

fearofawhackplanet