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

2

2

I have a popup window which disappears on click inside, but my purpose is to make it disappear on click outside.

At the moment the popup works fine but it disappears whenever I click inside the window. When I click outside the window, it stays. How do I make it work the oppersite way around?

Code as:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('.invite_room_btn').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('.invite_room_btn'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And HTML is:

<span class="invite_room_btn">
            <div class="messagepop pop">
            </div>
</span>

Thanks!

Mcminn answered 17/2, 2015 at 9:42 Comment(0)
T
15

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/

Tribunate answered 17/2, 2015 at 10:4 Comment(0)
M
1

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!

Mcminn answered 17/2, 2015 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.