How do I check if the mouse is over an element in jQuery?

Steve Wortham picture Steve Wortham · Aug 13, 2009 · Viewed 333.3k times · Source

Is there a quick & easy way to do this in jQuery that I'm missing?

I don't want to use the mouseover event because I'm already using it for something else. I just need to know if the mouse is over an element at a given moment.

I'd like to do something like this, if only there was an "IsMouseOver" function:

function hideTip(oi) {
    setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}

Answer

Arthur Goldsmith picture Arthur Goldsmith · Nov 3, 2009

This code illustrates what happytime harry and I are trying to say. When the mouse enters, a tooltip comes out, when the mouse leaves it sets a delay for it to disappear. If the mouse enters the same element before the delay is triggered, then we destroy the trigger before it goes off using the data we stored before.

$("someelement").mouseenter(function(){
    clearTimeout($(this).data('timeoutId'));
    $(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
    var someElement = $(this),
        timeoutId = setTimeout(function(){
            someElement.find(".tooltip").fadeOut("slow");
        }, 650);
    //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
    someElement.data('timeoutId', timeoutId); 
});