Search code examples
jqueryhovermousemovemouseoutmouseleave

jQuery - How to check which element is being hovered over (but NOT any specific element!)


I would like to use jQuery to determine which element is currently being hovered over. It could be any element on the page, meaning that mouseover, mouseout, mouseenter, and mouseleave do not apply here, as they would relate to a specific element.

Here's a quick sample:

$(window).bind('mousemove', function() {
    if (elementBeingHoveredOver.attr('id') != 'foo') {
        // ... (Do some cool stuff here) ...
        $(window).unbind('mousemove');
    }
});

I know, I know, it looks like it would be better to bind a mouseenter and mouseleave event handler to the #foo element and just do it that way, but the mouse often moves too quickly to register a mouseleave event, so I want to try it this way.

Any ideas on how to determine elementBeingHoveredOver?


Solution

  • Try this

    $(window).bind('mousemove', function(e) {
        if ($(e.target).attr('id') != 'foo') {
            // ... (Do some cool stuff here) ...
            $(window).unbind('mousemove');
        }
    });