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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-14 10:51:02669browse

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

Bootstrap 3: Solving the Persisting Collapsed Menu Issue

Problem:

In a Bootstrap 3 navigation, the collapsed menu remains open after clicking a menu link, disrupting the user experience.

Answer:

To resolve this issue, implement the following code:

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});

Details:

  • This solution binds an event listener to the document to monitor clicks within the expanded navigation menu (class: ".navbar-collapse.in").
  • When a click occurs on a menu link ("a" element), the line $(this).collapse('hide'); triggers the collapse of the navigation menu.

Update [2014-11-04]:

  • For navigation with submenus, modify the code to:
$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a:not(".dropdown-toggle")') ) {
        $(this).collapse('hide');
    }
});
  • This modification ensures that only menu links that are not dropdown toggles trigger the menu collapse.

The above is the detailed content of Why Does My Bootstrap 3 Collapsed 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