Bootstrap 3 Collapsed Navigation Menu Remains Open on Click
Bootstrap 3's navigation menus have a convenient collapse feature for smaller devices. However, the menu sometimes stays open after clicking on a menu link. This can be frustrating if you want the menu to close after selecting an item.
The code below, which was a popular solution on GitHub, solves this issue:
$(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a') ) { $(this).collapse('hide'); } });
This code binds an event listener to the document, which listens for clicks on any element within the expanded navbar-collapse. If the clicked element is an anchor element, it collapses the menu.
To address issues with sub-menus, the code was modified as follows:
$(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a:not(".dropdown-toggle")') ) { $(this).collapse('hide'); } });
This ensures that the menu only collapses when the clicked element is a direct link, not a dropdown toggle.
The above is the detailed content of Why Does My Bootstrap 3 Collapsed Navigation Menu Stay Open After Clicking a Link?. For more information, please follow other related articles on the PHP Chinese website!