Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click inside/outside of element with single event handler

Suppose I have one div in my page. how to detect the user click on div content or outside of div content through JavaScript or JQuery. please help with small code snippet. thanks.

Edit: As commented in one of the answers below, I only want to attach an event handler to my body, and also want to know which element was clicked upon.

like image 663
Thomas Avatar asked Jan 11 '11 17:01

Thomas


People also ask

How do I detect a click outside an element?

To detect click outside element with JavaScript, we can use the element's contains method. const specifiedElement = document. getElementById("a"); document. addEventListener("click", (event) => { const isClickInside = specifiedElement.

How do you detect outside click in react JS?

Detecting an outside click of a functional component Let's build an HTML tooltip by creating a React functional component named InfoBox . The tooltip will appear when the user clicks a button, and it will be closed if the user clicks outside of the tooltip component.

How do you check if a click is outside a div?

addEventListener('click', function(e){ if (document. getElementById('clickbox'). contains(e. target)){ // Clicked in box } else{ // Clicked outside the box } });


1 Answers

Here's a one liner that doesn't require jquery using Node.contains:

// Get arbitrary element with id "my-element" var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element'); // Listen for click events on body document.body.addEventListener('click', function (event) {     if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {         console.log('clicked inside');     } else {         console.log('clicked outside');     } }); 

If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true) so this snippet should always work.

Browser support seems to cover pretty much everything according to that MDN page as well.

like image 55
KhalilRavanna Avatar answered Oct 28 '22 09:10

KhalilRavanna