jQuery: Hide popup if click detected elsewhere

前端 未结 12 858
情书的邮戳
情书的邮戳 2020-12-02 14:33

I\'m trying to hide a div if the user clicks anywhere BUT the popup OR its children. This is the code I have so far:

$(\"body\").click(function(){
    var $t         


        
12条回答
  •  盖世英雄少女心
    2020-12-02 14:51

    You really could simplify this a bit I think:

    // If an event gets to the body
    $("body").click(function(){
      $(".popup").fadeOut().removeClass("active");
    });
    
    // Prevent events from getting pass .popup
    $(".popup").click(function(e){
      e.stopPropagation();
    });
    

    Clicking on the popup, or any of its children will cause propagation to stop before it reaches the body.

    Demo of stopping event-propagation: http://jsbin.com/ofeso3/edit

提交回复
热议问题