简体   繁体   中英

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?

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
    }
});

Your event handler gets passed an event object, not an element. Since you are listening for the click event, the event will be of type MouseEvent and that event object will have a target property which you can use to check if the target element matches your desired element.

function handler(event) {
    if (event.target == document.getElementById("panel")) {    
        // Do stuff
    }
}

document.addEventListener('click', handler);

Edit: I intentionally gave the vanilla JS answer since your own code fragments don't use jQuery. But jQuery wouldn't change anything as its event handling API is almost just a thin wrapper over JS.

I am just using event from the click. Here it is

var elem=document.getElementById("elem");
var rects=elem.getBoundingClientRect();//get the bounds of the element

document.addEventListener('click', print);

function print(e)
{  
 //check if click position is inside or outside target element
 if(e.pageX<= rects.left +rects.width && e.pageX>= rects.left &&  e.pageY<= rects.top +rects.height && e.pageY>= rects.top){
    console.log("Inside element");
 }   
 else{
   console.log("Outside element");
}
}

JS Bin link : https://jsbin.com/pepilehigo/edit?html,js,console,output

A different approach, using only javascript is:

 function print(evt) { if (!(evt.target.tagName == 'DIV' && evt.target.classList.contains('myDiv'))) { var div = document.createElement('div'); div.classList.add('myDiv'); div.textContent="new div"; document.body.appendChild(div); } } window.onload = function() { document.addEventListener('click', print); } 
  .myDiv { border:1px solid green; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM