Skip to content
Advertisement

hide sidebar when click anywhere in page

I have an animate sidebar which appears when user clicks on a hamburger button. Here is the structure :

$('#nav-toggle').click(function() {
  if($('#nav-toggle').hasClass('active')){
    $('.menu').animate({
      right: "0px"
    }, 200);
  }else{
    $('.menu').animate({
      right: "-285px"
    }, 200);
  }

});
.menu{
    right:-285px;
    height:100%;
    position: fixed;
    width: 285px;
    z-index: 1;
    background-color: #111111;
}
.menu ul {
  border-top: 1px solid #636366;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  border-bottom: 1px solid #636366;
  font-family: 'Open Sans', sans-serif;
  line-height: 45px;
  padding-bottom: 3px;
  padding-left: 20px;
  padding-top: 3px;
}
.menu li a{
    color:white;
}
    <div class="menu">
      <!-- Menu -->
      <ul>
        <li><a href="#">About</a></li>
        <li><a href="#">Blog</a></li>
        <li><a href="#">Help</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </div>

Actually we can open menu by clicking on #nav-toggle element and close it by clicking on this element too. I’d like to allow user to close this menu by clicking anywhere in the page. How can I do do that? I tried with e.preventDefault(); in my if statement but it doesn’t work.

Thanks!

Advertisement

Answer

I suggest to use toggleClass method and animate it by adding transition: .2s to your .menu, working example:

$('#nav-toggle').click(function(e) {
  e.stopPropagation();
  $(".menu").toggleClass('bar')
});
$('body').click(function(e) {
  if ($('.menu').hasClass('bar')) {
    $(".menu").toggleClass('bar')
  }
})
.menu {
  right: -285px;
  height: 100%;
  position: fixed;
  width: 285px;
  z-index: 1;
  background-color: #111111;
  transition: .2s
}

.menu ul {
  border-top: 1px solid #636366;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  border-bottom: 1px solid #636366;
  font-family: 'Open Sans', sans-serif;
  line-height: 45px;
  padding-bottom: 3px;
  padding-left: 20px;
  padding-top: 3px;
}

.menu li a {
  color: white;
}

.bar {
  right: 0px;
}

body,
html {
  height: 100%;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="nav-toggle">Click me</button>
<div class="menu">
  <!-- Menu -->
  <ul>
    <li><a href="#">About</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Help</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement