Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcelo-ribeiro/3592b3e5991e52f4588e820758e7aaa6 to your computer and use it in GitHub Desktop.
Save marcelo-ribeiro/3592b3e5991e52f4588e820758e7aaa6 to your computer and use it in GitHub Desktop.
How to detect a click outside of an element with vanilla JavaScript

How to detect a click outside of an element with vanilla JavaScript

A simple way to detect a click outside of an element with vanilla JavaScript

A Pen by Marcelo Ribeiro on CodePen.

License.

<button>Toggle box</button>
<div class="box">
<form action="">
<input type="text">
<button type="button">Search</button>
</form>
</div>
// Example
const button = document.querySelector('button')
const box = document.querySelector('.box');
const toggle = event => {
event.stopPropagation();
if (!event.target.closest('.box')) {
console.log('Click outside');
box.classList.toggle('active');
box.classList.contains('active')
? document.addEventListener('click', toggle)
: document.removeEventListener('click', toggle);
} else {
console.log('Click inside');
}
}
button.addEventListener('click', toggle);
.box {
position: absolute;
display: none;
margin-top: 8px;
padding: 20px;
background: lightgray;
&.active {
display: block;
}
}
@Zahra-ellioun
Copy link

nkljm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment