简体   繁体   中英

Toggle menu only when it is open when we click anywhere on window

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM