Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide menu sidebar when clicking outside the bar or the button

I am trying to make a menu like the semantic UI but I only achieved to click the menu button and open the menu and vice versa. I use toggle class to show the sidebar but I dont know if this way is completely right:

<div class="menu-button" id="menu-button"></div>

$('#menu-button').click(function(event) {
     $('#hide-menu').toggleClass('show-menu');
});

.hide-menu {
    background-color:#336ca6;
    position: absolute;
    top:0;
    right:0;
    z-index: 1;
    width: 300px;
    height: 100%;
    -webkit-transform: translate3d(300px,0,0);
    -moz-transform: translate3d(300px,0,0);
    -o-transform: translate3d(300px,0,0);
    -ms-transform: translate3d(300px,0,0);
    transform: translate3d(300px,0,0);      
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -ms-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
    transition: all 0.3s linear;
}

.show-menu {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -o-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
 }  

I've tried the event propagation but I can't manage to make it play.

like image 944
DMande Avatar asked Apr 30 '15 06:04

DMande


People also ask

How do you hide the sidebar in CSS?

Hide the "sidebar" => add a "hidden" class to it, Make the "content" fill the whole screen => add a "full-width" class.

How do I open and close the sidebar?

Opening and closing the Sidebar can be achieved with built-in public methods. show() : Method to open the Sidebar. hide() : Method to close the Sidebar. toggle() : Method to toggle between open and close states of the Sidebar.


2 Answers

Edit your js code to following

$('#menu-button').click(function(e){
    e.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});

$('#hide-menu').click(function(e){
    e.stopPropagation();
});

$('body,html').click(function(e){
   $('#hide-menu').removeClass('show-menu');
});

Hope this will work.

Here is fiddle. http://jsfiddle.net/ex8ddv5q/1/

like image 149
murli2308 Avatar answered Oct 26 '22 23:10

murli2308


For a different take on it check this Fiddle

$('#menu-button').click(function (evt) {
    evt.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});


$('body,html').click(function (e) {

    var container = $("#hide-menu");

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.removeClass('show-menu');

    }
});
like image 38
R4nc1d Avatar answered Oct 26 '22 23:10

R4nc1d