How to hide the popup by clicking on the button

I'm trying to come up with a way so that after I see the message # email-popup or # phone-popup, if the user clicks anywhere, EXCEPT a visible pop-up window, it will hide the pop-up window.

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

My jQuery bye

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

$(document).click(function() {
     $("#email-popup").hide("fast");                        
     $("#phone-popup").hide("fast");
});
+3
source share
3 answers

You're close - just stop sharing when the user clicks on pop-ups:

$("#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 the repeated code in the click of the document. You hide the pop-up email twice.

$(document).on("click", function() {
  $("#email-popup, #phone-popup").hide("fast");
});
+5
source

You can check the id of the element that clicked (will not work with child 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

+2

How about this not working? What's happening? By the way, you are hiding #email-popuptwice in your handler click.

+1
source

All Articles