John Boe
John Boe

Reputation: 3611

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?

Upvotes: 0

Views: 3643

Answers (4)

gaetanoM
gaetanoM

Reputation: 42044

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

Upvotes: 0

eisbehr
eisbehr

Reputation: 12452

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

Upvotes: 1

The_ehT
The_ehT

Reputation: 1230

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

Upvotes: 0

Can Ibanoglu
Can Ibanoglu

Reputation: 604

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.

Upvotes: 0

Related Questions