简体   繁体   中英

Close DIV popup clicking outside of it

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>
$(document).click(function(event) {
    if ( $(event.target).closest(".myPopup").get(0) == null ) {         
    alert('clicked outside');           
    } else{
    alert('clicked inside');
    }
});

This works for me.

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 );

Try:

document.onmousedown = function(){
    if(event.target.className != 'myPopup')
        document.getElementsByClassName('myPopup')[0].style.display = 'none';
}
$('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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM