Home >Web Front-end >CSS Tutorial >How to Automatically Close a Bootstrap Responsive Menu on Item Click?
Bootstrap: Auto-Close Responsive Menu on Menu Item Click
When displaying responsive menus in Bootstrap, you may want to automatically close the menu after a menu item is clicked on a mobile or tablet device while retaining the open state on desktop.
Issue:
The user attempted to use $('.btn-navbar').click(); and $('.nav-collapse').toggle(); to achieve this behavior, but it caused the menu to shrink unexpectedly on desktop.
Solution:
To resolve this issue, modify your menu items to include data-toggle and data-target attributes, as you would with theNavbar toggle button. For instance, for the "Products" menu item:
<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>
Repeat this for each menu item.
Additional Fixes:
To address overflow issues and flickering, add the following code:
<li><a href="#products" class="hidden-xs">Products</a></li> <li><a href="#products" class="visible-xs" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>
This will make the toggle and target selectors screen size-specific, eliminating glitches on the larger menu.
Bootstrap Version Updates:
By implementing these modifications, you can automatically close the responsive menu on menu item clicks while maintaining its functionality on desktop devices.
The above is the detailed content of How to Automatically Close a Bootstrap Responsive Menu on Item Click?. For more information, please follow other related articles on the PHP Chinese website!