Click Outside Close Menu Box Tutorial
In this JavaScript exercise we will demonstrate how to close specific things when a user clicks outside of them. You may have drop down menus that you want to close when a user interacts with other things on the page. Or perhaps you have information windows that appear over content and you want to close them if the user clicks outside of them.
Closing multiple magic menus or boxes
var boxArray = ['box1','box2','box3'];
window.addEventListener('mouseup', function(event){
for(var i=0; i < boxArray.length; i++){
var box = document.getElementById(boxArray[i]);
if(event.target != box && event.target.parentNode != box){
box.style.display = 'none';
}
}
});
Closing single elements
window.addEventListener('mouseup', function(event){
var box = document.getElementById('box1');
if (event.target != box && event.target.parentNode != box){
box.style.display = 'none';
}
});