How to identify when a click is made outside the popup window?

余生长醉 提交于 2019-12-02 00:47:47
Danilo

Your question can be interpreted as "how to identify when the click is made outside the popup window"?

as suggested here, you can work by difference, checking that the click occurred anywhere but the popup window (and eventually some other elements)

This can be achieved as follows:

the HTML code may be something like:

<div id="popup" class="popup"> 
    Content
    <div>DIV inside</div>
</div>
<button id="open">Open</button>

while the javascript is:

 $(document).ready(function () {
     $('#popup').hide()
 });

 $('#open').on('click', function () {
     $('#popup').show(500)
 });

 $(document).mouseup(function (e) {
     var popup = $("#popup");
     if (!$('#open').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
         popup.hide(500);
     }
 });

Full example with some CSS-styling: http://jsfiddle.net/sLdmxda8/2/

I figured it out with the following code!

$(document).ready(function () {
$('.messagepop').hide()
});


$('.invite_room_btn').on('click', function () {
    if($(this).hasClass("selected")) {
        var popup = $(".messagepop");
        popup.hide(150);
        $(".invite_room_btn").removeClass("selected");
    }
    else {
        $('.messagepop').show(150);
        $('.invite_room_btn').addClass("selected");
    }
});

$(document).mouseup(function (e) {
    var popup = $(".messagepop");
    if (!$('.invite_room_btn').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
        popup.hide(150);
 }
});

Thanks for the help!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!