最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When I click anywhere in body toggle jQuery hide automatically - Stack Overflow

programmeradmin1浏览0评论

I use show hide Slide toggle for hide my login panel. When I click on LogIn button it shows and when I again click in logIn button it hides, but I want that when I click on logIn button it show and when I click anywhere in body it hide automatically.

<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
    $('#showmenu').click(function() {
            $('.login-wrapper').slideToggle();
    });
});
</script>

I use show hide Slide toggle for hide my login panel. When I click on LogIn button it shows and when I again click in logIn button it hides, but I want that when I click on logIn button it show and when I click anywhere in body it hide automatically.

<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
    $('#showmenu').click(function() {
            $('.login-wrapper').slideToggle();
    });
});
</script>
Share Improve this question edited Mar 30, 2015 at 11:22 tutankhamun 9302 gold badges11 silver badges23 bronze badges asked Mar 21, 2014 at 5:17 SamSam 373 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Have a click event bound to the document object

$(document).ready(function () {
    $('#showmenu').click(function (e) {
        $('.login-wrapper').stop(true).slideToggle();
    });
    $(document).click(function (e) {
        if (!$(e.target).closest('#showmenu, .login-wrapper').length) {
            $('.login-wrapper').stop(true).slideUp();
        }
    });
});

Demo: Fiddle

You can add a .click handler to the document level to slide up the .login-wrapper.

But when you use it like that then when .login-wrapper is opened by clicking on the button #showmenu, the click will be bubble up on the DOM tree and fire the click event at the document level as well which will close your .login-wrapper again eventually.

That's why you need to make use of e.stopPropagation() here to prevent bubble up the DOM tree so your .login-wrapper will not be closed if you click on the button.

$(document).ready(function () {
    $(document).click(function () {
        $('.login-wrapper').slideUp();
    });
    $('#showmenu').click(function (e) {
        e.stopPropagation();
        $('.login-wrapper').slideToggle();
    });
});

Fiddle Demo


Based on your ment, you can use:

$(document).ready(function () {
    $(document).click(function () {
        $('.login-wrapper').slideUp();
    });
    $('#showmenu').click(function (e) {
        e.stopPropagation();
        $('.login-wrapper').slideToggle();
    });
    $('.login-wrapper').click(function (e) {
        e.stopPropagation();
    });
});

Updated Fiddle

发布评论

评论列表(0)

  1. 暂无评论