Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  199] [ 4]  / answers: 1 / hits: 15654  / 8 Years ago, sat, april 16, 2016, 12:00:00

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!


More From » jquery

 Answers
7

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>




[#62529] Thursday, April 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
latrelllloydb

Total Points: 449
Total Questions: 92
Total Answers: 100

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;