How to hide a popup by clicking outside

后端 未结 3 568
醉酒成梦
醉酒成梦 2020-12-21 10:55

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 po

相关标签:
3条回答
  • 2020-12-21 11:04

    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

    0 讨论(0)
  • 2020-12-21 11:14

    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");
    });
    
    0 讨论(0)
  • 2020-12-21 11:15

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

    0 讨论(0)
提交回复
热议问题