Click outside div to hide div in pure JavaScript

Here is the second version which has a transparent overlay as asked by the asker in the comments…

window.onload = function(){
	var popup = document.getElementById('popup');
    var overlay = document.getElementById('backgroundOverlay');
    var openButton = document.getElementById('openOverlay');
    document.onclick = function(e){
        if(e.target.id == 'backgroundOverlay'){
            popup.style.display = 'none';
            overlay.style.display = 'none';
        }
        if(e.target === openButton){
         	popup.style.display = 'block';
            overlay.style.display = 'block';
        }
    };
};
#backgroundOverlay{
    background-color:transparent;
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    display:block;
}
#popup{
    background-color:#fff;
    border:1px solid #000;
    width:80vw;
    height:80vh;
    position:absolute;
    margin-left:10vw;
    margin-right:10vw;
    margin-top:10vh;
    margin-bottom:10vh;
    z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
    <div id="backgroundOverlay"></div>
    <input type="button" id="openOverlay" value="open popup">

Here is the first version…

Here is some code. If there is anything else to add, please let me know 🙂

The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.

window.onload = function(){
  var divToHide = document.getElementById('divToHide');
  document.onclick = function(e){
    if(e.target.id !== 'divToHide'){
      //element clicked wasn't the div; hide the div
      divToHide.style.display = 'none';
    }
  };
};
<div id="divToHide">Click outside of this div to hide it.</div>

Leave a Comment