To ensure that your wrapper element covers your parent window but stays below the popup window, follow these steps:
First, create a wrapper element with a higher z-index than the parent window.
Add an event listener for "click" to this wrapper element.
If the click target matches the wrapper element, close the popup and delete the wrapper element itself.
This setup will manage clicks outside of the popup effectively.
Remember to handle other events within your window accordingly.
Additional Styles
html {
height: 100%;
}
body {
position: relative;
height: 100%;
z-index: 1;
}
#overlay {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.25);
z-index: 99;
}
#popup {
position: absolute;
width: 20%;
height: 20%;
top: 40%;
left: 40%;
background: rgb(220,220,220);
box-shadow: 2px 2px 3px rgba(0,0,0,0.5);
z-index: 100;
}
HTML Code
<input id="popupbutton" type="button" value="pop me up" />
Javascript Logic
<script>
document.getElementById('popupbutton').addEventListener('click', loadPopup, true);
function loadPopup(e) {
e.preventDefault();
e.stopPropagation();
var overlay = document.createElement('div');
overlay.id = 'overlay';
overlay.addEventListener('click', closePopup, true);
var popup = document.createElement('div');
popup.id = 'popup';
document.body.appendChild(overlay);
document.body.appendChild(popup);
function closePopup(e) {
e.preventDefault();
e.stopPropagation();
// Close everything only if clicked on overlay
if (e.target.id === 'overlay') {
document.body.removeChild(popup);
document.body.removeChild(overlay);
}
}
}
</script>
Updated JS Fiddle Link
http://jsfiddle.net/md063bfr/1/