user1141649 user1141649 - 4 months ago 8
Javascript Question

How to detect if mouse cursor is out of element?

I have a listener which runs when I click on document.

document.addEventListener('click', print);

function print(element)
{
doSomething();
}


It creates div id=panel, where I print some information.

When I run the print function I would like to detect whether I clicked outside of the div#panel (The panel exists when I click second time).

I wish not to use the mouseout event listener because I think it is redundant to use listener for mouse movements when the event click is already fired.

How to detect when I clicked out of div#panel?

Answer

You can check the target of jQuery's click event, which element it was:

$(document).click(function(e) {
    var target = $(e.target);

    if( !target.is("#panel") && target.closest("#panel").length === 0 ) {
        // click was not on or inside #panel
    }
});