Home >Web Front-end >CSS Tutorial >How to Automatically Close a Bootstrap Responsive Menu on Item Click?

How to Automatically Close a Bootstrap Responsive Menu on Item Click?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 22:03:02616browse

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:

  • Bootstrap v4.1.3 & v5.0: Replace visible/hidden classes with d-none d-sm-block and d-block d-sm-none.
  • Bootstrap v5: Replace data-toggle with data-bs-toggle and data-target with data-bs-target.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn