Home >Web Front-end >CSS Tutorial >Why Does My Bootstrap 3 Collapsed Navigation Menu Stay Open After Clicking a Link?

Why Does My Bootstrap 3 Collapsed Navigation Menu Stay Open After Clicking a Link?

DDD
DDDOriginal
2024-12-22 08:25:10667browse

Why Does My Bootstrap 3 Collapsed Navigation Menu Stay Open After Clicking a Link?

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!

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