Ian Wise
Ian Wise

Reputation: 766

JavaScript, detect when the mouse cursors is not over any element

Maybe there is a simple solution to this that I'm overlooking, however I cannot find anything in my research that answers this question.

I want to know if my mouse cursor is not hovering over ANY element

For example, say my page has one textbox. When the mouse cursor moves over the textbox, nothing happens. When the mouse cursor leaves the textbox, this event fires.

I've tried the following, however the event always fires.

window.addEventListener('mousemove', function(event){
    if (event.target === document.body){
        console.log('fire');
    }
});

As always, performance is a major consideration.

Upvotes: 1

Views: 806

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

Try following

window.addEventListener('mousemove', function(event){
    if (event.target.tagName === "HTML" || event.target.tagName === "BODY"){
        console.log('fire');
    }
});
<div>My content</div>

Upvotes: 2

Related Questions