简体   繁体   中英

Open/close mobile menu on other button click

I'm struggeling to create/finish an app like menu for a mobile site.

When clicking a button in the nav then there's a menu popup showed. When I click that same button again it nicely closes. However when the popup is opened and I click another button in the navbar then both menu's are overlaying each other.

I'm struggeling to get my logic right. Since toggeling classes won't work. I'm working to long on this so perhaps I miss something simple/stupid.

I've created a fiddle here to better explain the problem.

Any help appreciated.

 $(function() { var $body = $("body"), $btn = $(".menuButton"), $menu = $(".mobile-menu"); $btn.one('click', function() { $body.append('<div class="mobile-menu-overlay" />'); }); $btn.on('click', function() { $(this).siblings().removeClass('open'); var $open_menu = $(this).data('open'); $menu.find('.' + $open_menu).toggle() if ($(this).hasClass('open')) { $(this).removeClass('open') $body.removeClass('mobile-open') $(this).closest($menu).removeClass('open') } else { $(this).addClass('open') $body.addClass('mobile-open') $(this).closest($menu).addClass('open') } // $(this).siblings().removeClass('open'); // var $open_menu = $(this).data('open'); // $menu.find('.'+$open_menu).toggle() // $(this).toggleClass('open') // $body.addClass('mobile-open') // $(this).closest($menu).addClass('open') }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mobile-nav"> <ul> <li class="search menuButton" data-open="search"><span>Search</span></li> <li class="menu menuButton" data-open="nav"><span>Menu</span></li> <li class="cart menuButton" data-open="cart"><span>Cart</span></li> <li class="account menuButton" data-open="account"><span>Account</span></li> </ul> </div> <div class="mobile-menu"> <div class="mobile-section top-section open"> <div class="section-content"> <div class="account" style="background:yellow">account content</div> <div class="cart" style="background:blue">cart</div> <div class="search" style="background:orange">search</div> <ul class="nav" style="background:green"> <li class="has-children"> <a href="url" title="title">category-title <span class="menu-icon" data-slide="forward"> <i class="fa fa-chevron-right"></i> </span> </a> </li> </ul> </div> </div> </div>

The problem is here:

 $menu.find('.' + $open_menu).toggle()

when you toggle a menu, you should toggle off its siblings.

I suggest to handle this using classes so you can do something like this:

$menu.find('.'+$open_menu).addClass('menu_open').siblings().removeClass('menu_open'); 

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