A simple way to detect a click outside of an element with vanilla JavaScript
A Pen by Marcelo Ribeiro on CodePen.
A simple way to detect a click outside of an element with vanilla JavaScript
A Pen by Marcelo Ribeiro on CodePen.
<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; | |
} | |
} |
nkljm