4

I am trying to come up with a way so that once #email-popup or #phone-popup is visible, if the user clicks anywhere EXCEPT the visible popup, then it is going to hide the popup.

My method for hiding the popups in the code below does not work well...

My JQuery so far

$(".email").click(function(){
    $("#email-popup").show("fast");
});
$(".phone").click(function(){
   $("#phone-popup").show();
});

$(document).click(function() {
     $("#email-popup").hide("fast");                        
     $("#phone-popup").hide("fast");
});
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231

3 Answers3

7

You're close - just stop the propagation when the user clicks within the popups:

$("#email-popup, #phone-popup").on("click", function(e){
  e.stopPropagation();
});

$(".email").on("click", function(e){
  e.stopPropagation();
  $("#email-popup").show("fast");
});

$(".phone").on("click", function(e){
  e.stopPropagation();
  $("#phone-popup").show();
});

Also you have some repeated code in the document click. You're hiding the email popup twice.

$(document).on("click", function() {
  $("#email-popup, #phone-popup").hide("fast");
});
Sampson
  • 265,109
  • 74
  • 539
  • 565
2

You could check the ID of the element clicked (won't work on children of the elements) :

$(".email").click(function(e){
    e.stopPropagation();
    $("#email-popup").show("fast");
});
$(".phone").click(function(e){
    e.stopPropagation();
    $("#phone-popup").show("fast");
});

$(document).click(function(e) {
     if (!(e.target.id === 'email-popup' || e.target.id === 'phone-popup')) {
         $("#email-popup, #phone-popup").hide("fast");                        
     }
});

DEMONSTRATION

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • this does not work, it acts the same way as it did with the code posted above, popup just appears and disappears instantly... thanks though – AnchovyLegend May 19 '12 at 14:54
  • you should modify your comment to match your jquery from fiddle, your solution on jfiddle worked for me! but the one posted above did not :) thank you! – AnchovyLegend May 19 '12 at 15:08
1

What about it doesn't work well? What does happen? By the way, you're hiding #email-popup twice in your click handler.

JMM
  • 26,019
  • 3
  • 50
  • 55