user5227152
user5227152

Reputation:

Hide a DIV when the user clicks outside of it using jQuery

I am using this code:

$(document).ready(function(){
    $(".SlideDiv").hide();
    $(".Show_hide").show();

    $('.Show_hide').click(function(){
        $(".SlideDiv").slideToggle();
    });
});

And this HTML:

    <a href="#" class="Show_hide">Show/hide</a>
<div class="SlideDiv">this is content page
<a class="agree" href="https://www.google.com/" target="_blank">google</a>
</div>

And this CSS:

.SlideDiv
{  
    height:200px;
    background-color:gray;
    margin-top:10px;

}
.Show_hide
{
    display:none;
}

The problem is that I have links inside the DIV and when they click that link open but show function didn't hide.

Demo

Upvotes: 1

Views: 114

Answers (2)

rrk
rrk

Reputation: 15846

DEMO

No need to use any plugins for this. You just need to bind every click on the document to a function and check if the click was on an object is not any of the functional links. event.stopPropagation() is used to prevent bubbling of events.

$(document).ready(function(){
    $(document).on('click',function(e){
        if( !$(e.target).is('.Show_hide, .SlideDiv') || 		
            !$(e.target).parents('.Show_hide, .SlideDiv').length == 0){
            $(".SlideDiv").slideUp();
            e.stopPropagation();
        }
    });
    $(".SlideDiv").hide();
    $(".Show_hide").show();

    $('.Show_hide').click(function(){
        $(".SlideDiv").slideToggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a href="#" class="Show_hide">Show/hide</a>
<div class="SlideDiv">this is content page
<a class="agree" href="https://www.google.com/" target="_blank">google</a>
</div>

Upvotes: 0

Nishith Kant Chaturvedi
Nishith Kant Chaturvedi

Reputation: 4769

you can do this with a js "mousedownoutside.js" using following code

http://benalman.com/projects/jquery-outside-events-plugin/

    $('yourDiv').on('mousedownoutside', function(event){
    var target = $( event.target );
    if($(this) != target){
        $(this).slideUp();
    }

});

Upvotes: 1

Related Questions