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)?
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.
addEventListener('click', function(e){ if (document. getElementById('clickbox'). contains(e. target)){ // Clicked in box } else{ // Clicked outside the box } });
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With