user2162270
user2162270

Reputation:

Hide a div when clicked outside

I have the following HTML for a popup widget:

<div id="popup">
   <div class="popup-wrapper">
      <div class="content">
         <h1>TEST</h1>
      </div>
   </div>
</div>

Using CSS: it is displayed as NONE:

#popup {
    display: none;
    overflow: auto;
}

    #popup .popup-wrapper { 
        background-color: #0D1014; 
        background-color: rgba(13,16,20,0.95); 
        height: 100%; width: 100%;
        position: fixed; top: 0; left: 0; right: 0; bottom 0; 
    }

    #popup .content {
        background-color: #E8F0F3;
        border: 1px solid #FFFFFF;

        width: 300px;
        position: fixed;
        top: 50%; left: 50%;
        margin-left: -150px;
        margin-top: -140px;
        padding: 20px;
        overflow: hidden;

        border-radius: 5px 5px 5px 5px;
        -moz-border-radius: 5px 5px 5px 5px;
        -webkit-border-radius: 5px 5px 5px 5px;

        -webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
        -moz-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
        box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.5);
    }

    .no-scroll {
        overflow: hidden;
        height: 100%; width: 100%;
    }

With JavaScript The popup will be shown when a link is clicked:

$(".popup").on('click', function(e) {
        $("#popup").fadeIn(200);
        $("body").addClass("no-scroll");
    });

The problem is, how to hide the #popup when click on .popup-wrapper only and not .content?

Upvotes: 0

Views: 127

Answers (4)

Sumit
Sumit

Reputation: 708

Try below code:

jQuery('.popup-wrapper').click(function(){
   jQuery('#popup').hide();
});

Upvotes: 0

Yannick
Yannick

Reputation: 372

Just had this problem myself 20 min ago
Code:

$("#popup").on('click', function(e) {
    if ($(e.target).closest(".content" /*or any other selector here*/).length > 0) {return false;}
    $("#popup").fadeOut(200);
    $("body").addClass("no-scroll");
});

Upvotes: 1

Barmar
Barmar

Reputation: 781068

Use the :not pseudo-selector to filter out the .content DIV:

$(".popup-wrapper:not(.content)").click(...)

Upvotes: 0

j08691
j08691

Reputation: 207901

You could prevent any clicks on .content from propagating by adding this:

$('.content').click(function(e){ e.stopPropagation() })
$('#popup').click(function(){ $(this).fadeOut() })

Upvotes: 0

Related Questions