Reputation: 21
I have this code and I want to close this <div>
popup by clicking outside of it and not only by clicking on the close button.
How can I do that?
<script language="JavaScript">
<!--
function displayPopup(alert_MSG) {
var theDetail = document.getElementById(alert_MSG);
theDetail.style.display="block";
}
function closePopup(alert_MSG) {
var theDetail = document.getElementById(alert_MSG);
if (theDetail.style.display=="block") {
theDetail.style.display="none";
}
}
-->
</script>
Here is the HTML link:
<a href="javascript:displayPopup(<?=$id_pic?>)">open div here</a>
And is here my popup:
<div id="<?=$id_pic?>" class="myPopup" style="display:none;">
<div class="closeButton">
<a href="javascript:closePopup(<?=$id_pic?>)">Close</a>
</div>
Popup content here
</div>
Upvotes: 2
Views: 11708
Reputation: 3849
Watch this for webkit. CodePen.IO
#overlay {
top: 0;
position: absolute;
width: 100%;
height: 100%;
background-color: red;
z-index: 40;
}
With:
document.getElementById("overlay").addEventListener("click", closePopup, false );
document.getElementById("popup").addEventListener("click", stopPropagation, false );
Upvotes: 3
Reputation: 1665
$(document).click(function(event) {
if ( $(event.target).closest(".myPopup").get(0) == null ) {
alert('clicked outside');
} else{
alert('clicked inside');
}
});
This works for me.
Upvotes: 4
Reputation: 7549
$('body').click(function(){
$(".myPopup").hide();
});
Edit:
Maybe you can wrap your code in this:
<body>
<a href="javascript:closePopup(<?=$id_pic?>)" style="curser:default">
// all your code
</a>
</body>
Upvotes: 0
Reputation: 12683
Try:
document.onmousedown = function(){
if(event.target.className != 'myPopup')
document.getElementsByClassName('myPopup')[0].style.display = 'none';
}
Upvotes: 0