22

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
Hidden Hobbes
  • 13,893
  • 3
  • 38
  • 64
Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • Regardless of what you *want* to head, `hover` is the cross-browser option here, `mouseover` or `mouseenter` is the easiest cross-browser way to keep track of the hovered element. Also your phrasing is a bit off, the mouse is never *under* an element, it's *over* it. – Nick Craver Aug 03 '10 at 09:52
  • if you won't use hover, how will you know that the mouse enter that box of yours?... – Reigel Gallarde Aug 03 '10 at 09:52
  • 1
    @Reigel, look at mouse coordinates and look at div position. – Max Frai Aug 03 '10 at 09:53
  • [I contributed a pseudo-expression for it hoping that that helps someone though](http://stackoverflow.com/a/13942214/417685) – Alexander Dec 22 '12 at 15:05
  • @NickCraver: Checking cursor coordinates _can_ be necessary. For example, if you add an element positioned under the cursor, the `mouseover`/`mouseenter` event will not trigger on the element until the user moves the mouse. – Roy Tinker Apr 11 '13 at 17:26
  • Can't add a full answer b/c Q is closed, but try something based on the object returned by: document.querySelectorAll( ":hover" ); – Lorien Brune Oct 13 '22 at 22:00

5 Answers5

11

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,474
  • 11
  • 10
  • 3
    +1 I like this solution a lot. Don't you just need `return $(selector).data('hover');` at the end though? – fearofawhackplanet Aug 03 '10 at 11:11
  • 2
    This is not a complete answer: How do you initialize 'hover' to begin with? 'hover' is unknown until the pointer enter or exit the border of an element. – worldsayshi Nov 19 '12 at 09:46
  • Ah, my bad; to account for this, assume that the pointer is outside the element on initialization. 'hover' will be triggered at each movement of the pointer over the element, not just on enter. Although this still leaves the very small case of needing to know where the pointer is on initialization without moving it. Not a problem of mine though. – worldsayshi Nov 19 '12 at 09:55
  • this was the damned piece of the puzzle missing for me. coupled with mouseleave instead of mouseout, I feel I start to gain control on the hovering event. – Félix Adriyel Gagnon-Grenier Feb 19 '14 at 00:12
  • You might want to throttle these functions, it may cause performance issues when implementing this on a page with lots of elements. The `*` selector is already known to be slow, initiating lots of listeners can make that worse. – luukvhoudt Dec 07 '17 at 15:48
9

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");
Alexander
  • 23,432
  • 11
  • 63
  • 73
3

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
  • 52,166
  • 53
  • 160
  • 253
2

Can't you just check $(select).is(':hover') ?

  • 4
    Downvoting to saves people time, as this solution isn't an option anymore with jQuery 1.8 and newer. jQuery 1.8 deprecated `.is(':hover')`: http://stackoverflow.com/a/12517725/5295. – avernet Aug 10 '13 at 00:34
1

I did this with custom function:

$(document).mouseup(function(e) { 
     if(UnderElement("#myelement",e)) {
         alert("click inside element");
     }
});

function UnderElement(elem,e) {
     var elemWidth = $(elem).width();
     var elemHeight = $(elem).height();
     var elemPosition = $(elem).offset();
     var elemPosition2 = new Object;
     elemPosition2.top = elemPosition.top + elemHeight;
     elemPosition2.left = elemPosition.left + elemWidth;

     return ((e.pageX > elemPosition.left && e.pageX < elemPosition2.left) && (e.pageY > elemPosition.top && e.pageY < elemPosition2.top))
 }
domagojk
  • 1,020
  • 2
  • 11
  • 25