Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click outside element (vanilla JavaScript)

Tags:

javascript

I have searched for a good solution everywhere, yet I can't find one which does not use jQuery.

Is there a cross-browser, normal way (without weird hacks or easy to break code), to detect a click outside of an element (which may or may not have children)?

like image 265
Tiberiu-Ionuț Stan Avatar asked Jan 07 '13 01:01

Tiberiu-Ionuț Stan


People also ask

How do I detect a click outside an element JS?

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

How do I detect a click outside an element jQuery?

Answer: Use the event. target Propertytarget property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.

How do you hide a div when the user clicks outside of it using JavaScript?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.


1 Answers

Add an event listener to document and use Node.contains() to find whether the target of the event (which is the inner-most clicked element) is inside your specified element. It works even in IE5

var specifiedElement = document.getElementById('a');  //I'm using "click" but it works with any event document.addEventListener('click', function(event) {   var isClickInside = specifiedElement.contains(event.target);    if (!isClickInside) {     //the click was outside the specifiedElement, do something   } }); 

var specifiedElement = document.getElementById('a');    //I'm using "click" but it works with any event  document.addEventListener('click', function(event) {    var isClickInside = specifiedElement.contains(event.target);    if (isClickInside) {      alert('You clicked inside A')    } else {      alert('You clicked outside A')    }  });
div {    margin: auto;    padding: 1em;    max-width: 6em;    background: rgba(0, 0, 0, .2);    text-align: center;  }
Is the click inside A or outside?  <div id="a">A    <div id="b">B      <div id="c">C</div>    </div>  </div>
like image 186
fregante Avatar answered Oct 05 '22 11:10

fregante