jQuery: Hide popup if click detected elsewhere

前端 未结 12 804
情书的邮戳
情书的邮戳 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 15:00

    Brush up on your boolean logic! :)

    if(!$target.is(".popup") && !$target.parents().is(".popup"))
    
    0 讨论(0)
  • 2020-12-02 15:01

    Do this:

    $(document).click(function (e) {
        // show_alerts is the class of the link to display the popup
        if (!$(e.target).parents().andSelf().is('.show_alerts')) {
            // hide your popup
        }
    });
    

    example: http://jsfiddle.net/Acf3F/

    0 讨论(0)
  • 2020-12-02 15:03
    $("body").click(function(event ){
                var $target = $(event.target);
                if(!$target.parents().is(".popup") && !$target.is(".popup")){
                    $("body").find(".popup").hide();
                }
            });
    

    this is the solution for me

    0 讨论(0)
  • 2020-12-02 15:06

    Here is the code snippet which may help for a html structure

    <script>
    jQuery(document).click(function() {
            jQuery(".main-div-class .content").css("display","none");
        });
    
        jQuery(".main-div-class .content").click(function (e) {
            e.stopPropagation();
            //do redirect or any other action on the content
        });     
        jQuery(".main-div-class h4").click(function(e) {
            e.stopPropagation();
            jQuery(this).parent().find(".content").show();
        });
    </script>
    <div class="main-div-class">
    <h4>click here</h4>
    <div class='content'>to show content here like this "<a href="http://stackoverflow.com/questions/2329816/jquery-hide-popup-if-click-detected-elsewhere#new-answer">Click</a>" or any other type of content</div>
    </div>
    
    0 讨论(0)
  • 2020-12-02 15:12

    Here's a potential solution for certain situations. The popup must have tabindex set for this to work and cannot have any "focusable" elements inside.

    $('a').click(function() {
        $('.popup').show().focus();
    });
    $('.popup').blur(function() {
        $(this).hide();
    });
    

    http://jsfiddle.net/d6zw3/

    0 讨论(0)
  • 2020-12-02 15:13

    We are using this to show a popup on click and then hide it once you click the same button again or click outside.

    function togglePopup(){
      var selector = '#popup',
        $popup = $(selector),
        callback = function(e) {
          if (!$(e.target).parents().andSelf().is(selector)) {
            $popup.hide();
            $(document).off('click', callback);
          }
        };
    
      $popup.toggle();
      if ($popup.is(':visible')) {
        $(document).on('click', callback);
      }
      return false;
    }
    
    0 讨论(0)
提交回复
热议问题