Reputation: 1242
I am working on one scenario in that I have menu which toggle on one button. When I click on that Menu button it opens fine.
Problem persist with this code:
When I click on anywhere it toggle with open and close.
Now What I need is
When I click on anywhere on window menu should close but only when it is in open state. toggle only when it is in open state.
HTML Code :
<section id="wrapper"> <!-- Sidebar -->
<aside id="sidebar-wrapper">
<div class="togglebtn"><a href="#menu-toggle" id="menu-toggle"></a></div>
<ul class="sidebar-nav">
<li class="sidebar-brand"> <a href="#" class="ripple">
<div class="icon"><i class="demo-icon icon-meeter"></i></div>
<div class="nav-label"> <span>Dashboard</span></div>
</a>
</li>
</ul>
</div>
</aside>
</section>
JavaScript code:
<script>
$("#menu-toggle").click(function(e) {
e.preventDefault();
e.stopPropagation();
$("#wrapper").toggleClass("toggled");
});
$("body").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
</script>
Any help would be much appreciated.
Upvotes: 1
Views: 1906
Reputation: 58425
Just change your $("body").click
function:
$("body").click(function () {
$("#wrapper").removeClass("toggled");
});
Right now what's happening is that you are "toggling" the class every time any part of the body is clicked. Toggling turns a class on or off depending on its current state. You need to just ensure that it is removed when the body is clicked.
You can actually use toggleClass
to accomplish this, but you must tell it you are wanting to remove the class by passing it a state
parameter.
$("#wrapper").toggleClass("toggled", false);
See the jQuery documentation for toggleClass: http://api.jquery.com/toggleclass/
Upvotes: 1