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


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>

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();
    }

});
链接地址: http://www.djcxy.com/p/83650.html

上一篇: 无法显示溢出的div标签以外的内容

下一篇: 当用户使用jQuery在其外部点击时隐藏DIV