Home > Web Front-end > CSS Tutorial > How to Close Bootstrap 3 Collapsed Menu on Link Click?

How to Close Bootstrap 3 Collapsed Menu on Link Click?

Mary-Kate Olsen
Release: 2024-11-13 07:56:02
Original
566 people have browsed it

How to Close Bootstrap 3 Collapsed Menu on Link Click?

How to Close Bootstrap 3 Collapsed Menu on Link Click

Bootstrap 3's collapsed navigation menu provides a convenient way to hide and display navigation items on smaller devices. However, clicking on a menu link while the menu is expanded may not close it on click. This can be frustrating for users as it prevents easy navigation.

Solution

To address this issue, you can add the following code to your document:

$(document).on('click', '.navbar-collapse.in', function(e) {
  if ($(e.target).is('a:not(".dropdown-toggle")')) {
    $(this).collapse('hide');
  }
});
Copy after login

This code will listen for clicks within the collapsed menu and close the menu if the target element is not a dropdown toggle. By excluding dropdown toggles, you ensure that clicking on the dropdown menu itself does not close it.

Implementation

To implement this solution, you can include the code in your JavaScript file or add it directly to the bottom of the page before the closing tag.

Additional Notes

  • The original solution from GitHub, which only checked if the target was an 'a' element, could cause issues with sub-menus. The updated version checks for 'a:not(".dropdown-toggle")' instead to prevent this.
  • This solution only applies to Bootstrap 3.x. For Bootstrap 4 and above, the .in class has been replaced with .show.

The above is the detailed content of How to Close Bootstrap 3 Collapsed Menu on Link Click?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template