close side menu when clicked outside

倾然丶 夕夏残阳落幕 提交于 2021-02-17 03:59:25

问题


this is my code for a menu that comes in from the right side... heres is the js

jQuery(document).ready(function($) {
    var $toggleButton = $('.toggle-button'),
        $menuWrap = $('.menu-wrap'),
        $sidebarArrow = $('.sidebar-menu-arrow');
            $content = $('.content');
    // Hamburger button
    $toggleButton.on('click', function() {
        $(this).toggleClass('button-open');
        $menuWrap.toggleClass('menu-show');
        $content.toggleClass('content-background');
    });

    // Sidebar navigation arrows
    $sidebarArrow.click(function() {
        $(this).next().slideToggle(300);
    });
});

i want it to close automatically when clicked outside anywhere out side the menu. how can i do this.


回答1:


Simply do as follow:

       $(document).click(function (e)
        {
            var container = $(".toggle-button");
            if ((!container.is(e.target)))     // if the target of the click isn't the TOGGLE BUTTON... 
            {
                // Code to hide the menu
                $('.toggle-button').toggleClass('button-open');
                $('.menu-wrap').toggleClass('menu-show');
                $('.content').toggleClass('content-background');
            }
        });

That's it
Enjoy coding :)




回答2:


Hope this helps you.

$('body').click(function() {
   //add your code here to hide the menu
});


来源:https://stackoverflow.com/questions/42801614/close-side-menu-when-clicked-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!