Search code examples
javascriptjqueryhtmleventsdhtml

how do I know if the mouse pointer is on the HTML element?


I have a timed event I want to behave differently accordingly to what HTML element the mouse pointer is on.
Is there a way, assuming I have the HTML element, to know if the mouse pointer is currently on top of it.
I am well aware of the onmouseover/onmouseout events and how to use them.
I am using JQuery.
I am obviously looking for some kind of flag, as I need to check a state and not handle an event.
again, I know how to implement this with events.


Solution

  • I'm not aware of any built-in way to ping an element for the status of mouse hovering.

    However, you can create one by updating a flag at mouseenter and mouseleave -- which is where Brian Driscoll's suggestion of .hover comes in:

    jQuery.fn.tracking = function () {
      this.data('hovering', false);
    
      this.hover(function () {
        $(this).data('hovering', true);
      }, function () {
        $(this).data('hovering', false);
      });
    
      return this;
    };
    
    jQuery.fn.hovering = function () {
      return this.data('hovering');
    }
    

    You'll need to initialize tracking for each element you care about:

    $('#elem1,#elem2').tracking();
    

    But then you can get the status of any of them:

    if ($('#elem1').hovering()) {
        // ...
    } else if ($('#elem2').hovering()) {
        // ...
    }
    

    Demo: http://jsbin.com/amaxu3/edit