Table of Contents
1. Make sure the correct Bootstrap version and dependencies are introduced
2. Add manual closing logic (recommended method)
attribute" > Method 1: Use data-bs-dismiss="dropdown" attribute
Method 2: Manual control with JS
3. Check whether the default event is blocked
4. Behavioral differences when using anchor jumps
Home Web Front-end Bootstrap Tutorial Bootstrap navbar dropdown not closing on item select

Bootstrap navbar dropdown not closing on item select

Jul 18, 2025 am 02:32 AM

To solve the problem of not closing after clicking the option of Bootstrap navbar dropdown, first of all, you need to confirm that you are using Bootstrap 5 and correctly introduce dependencies; secondly, you can add the data-bs-dismiss="dropdown" attribute or manually control the closing with JS; at the same time, you can avoid abuse of e.preventDefault() to prevent the default behavior; in special scenarios such as anchor jump, you can combine other methods to deal with it. 1. Make sure to use Bootstrap 5 and load CSS and JS correctly; 2. It is recommended to add data-bs-dismiss="dropdown" on dropdown-item; 3. Or listen to click events through JS and call the dropdown.hide() method to close; 4. Be careful not to close the menu due to preventDefault(); 5. When the anchor jumps, you can combine scroll event processing to handle the closing logic according to the situation.

Bootstrap navbar dropdown not closing on item select

When using Bootstrap's navbar dropdown, many developers will encounter a problem: after clicking an option in the drop-down menu, the menu will not automatically close. Although this is not a bug in Bootstrap, it will indeed affect the user experience in actual development.

Bootstrap navbar dropdown not closing on item select

The core of this problem is that Bootstrap will not actively close the drop-down menu by default, unless the user clicks on the trigger area again or clicks elsewhere on the page. So how should we solve it?


1. Make sure the correct Bootstrap version and dependencies are introduced

First, make sure you are using Bootstrap 5 (currently mainstream version), because you no longer rely on jQuery since v5. If you are still using the old version of Bootstrap 4 or earlier, and cooperate with jQuery, there may be inconsistent behavior problems.

Bootstrap navbar dropdown not closing on item select

Check if the HTML is correctly introduced:

  • Bootstrap CSS
  • Bootstrap JS (preferably introduced via @popperjs/core and native ES Modules)

If you just copy and paste the code but don't load the necessary scripts, the dropdown behavior may be incomplete.

Bootstrap navbar dropdown not closing on item select

By default, clicking dropdown-item will not trigger the closing action. To turn it off, you need to manually add a piece of JavaScript to remove .show class or call the Bootstrap API.

Method 1: Use data-bs-dismiss="dropdown" attribute

This is the easiest way. Just add this attribute to each <a></a> tag:

 <a class="dropdown-item" href="#" data-bs-dismiss="dropdown">Home</a>

This way, every time you click this link, the drop-down menu will automatically close.

Method 2: Manual control with JS

If you do not want to modify the HTML structure, you can also control it through JS. For example, listen to all dropdown-item click events and then manually close:

 document.querySelectorAll(&#39;.dropdown-item&#39;).forEach(item => {
  item.addEventListener(&#39;click&#39;, () => {
    const dropdown = bootstrap.Dropdown.getInstance(item.closest(&#39;.dropdown-toggle&#39;));
    if (dropdown) {
      dropdown.hide();
    }
  });
});

Note that this code must be executed after the DOM is loaded, such as in DOMContentLoaded or introduced at the bottom of the body.


3. Check whether the default event is blocked

Sometimes we add e.preventDefault() to the link, for example, when making asynchronous requests, this may cause the menu to fail to close normally.

For example, the following situation:

 document.querySelector(&#39;.dropdown-item&#39;).addEventListener(&#39;click&#39;, function(e) {
  e.preventDefault(); // This will cause the default behavior to be blocked, including closing the menu // Doing some other operations...
});

At this time, even if you use data-bs-dismiss="dropdown" it will not take effect. So be careful not to abuse preventDefault() , or manually call hide() method after processing the logic.


4. Behavioral differences when using anchor jumps

If your dropdown-item is an ordinary anchor point (such as #section1 ) and you want the page to scroll past and close the menu after clicking, in addition to the above method, you can also consider combining scroll event or IntersectionObserver to determine whether the target position has reached, and then close the menu.

However, this kind of scenario is relatively rare, and most of the time, adding data-bs-dismiss="dropdown" is enough.


Basically that's it. This issue is not complicated but is easily overlooked, especially when dynamically generating menu items or binding events. Just remember that dropdown will not be turned off by itself, and you need to intervene manually.

The above is the detailed content of Bootstrap navbar dropdown not closing on item select. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
The Ultimate Guide to Creating Basic and Vertical Forms with Bootstrap The Ultimate Guide to Creating Basic and Vertical Forms with Bootstrap Jul 12, 2025 am 12:30 AM

The advantage of creating forms with Bootstrap is that it provides a consistent and responsive design, saving time, and ensuring cross-device compatibility. 1) Basic forms are simple to use, such as form-control and btn classes. 2) Vertical forms achieve a more structured layout through grid classes (such as col-sm-2 and col-sm-10).

Bootstrap Forms : Common errors Bootstrap Forms : Common errors Jul 14, 2025 am 12:28 AM

Bootstrapformscanleadtoerrorslikemisusingthegridsystem,improperformcontrols,validationissues,neglectingcustomCSS,accessibility,andperformance.Toavoidthese:1)Usecolumnclasseslikecol-sm-orcol-md-forresponsiveness;2)Wrapinputfieldsin.form-groupforproper

Bootstrap Grid System: A Beginner's Guide Bootstrap Grid System: A Beginner's Guide Jul 09, 2025 am 01:04 AM

Bootstrap'sGridSystemisessentialforcreatingresponsive,modernwebsites.1)Itusesa12-columnlayoutforflexiblecontentdisplay.2)Columnsaredefinedwithinrowsinsideacontainer,withwidthslikecol-6forhalf-width.3)Responsivenessisachievedusingclasseslikecol-sm-6fo

Bootstrap Grid System: A Comprehensive Guide for Responsive Layouts Bootstrap Grid System: A Comprehensive Guide for Responsive Layouts Jul 12, 2025 am 01:23 AM

Bootstrap'sGridSystemhelpsinbuildingresponsivelayoutsbyofferingflexibilityandeaseofuse.1)Itallowsquickcreationofadaptablelayoutsacrossdevices.2)Advancedfeatureslikenestedrowsenablecomplexdesigns.3)Itencouragesaresponsivedesignphilosophy,enhancingcont

Bootstrap Forms: Best template for quick win Bootstrap Forms: Best template for quick win Jul 07, 2025 am 01:36 AM

Bootstrapformtemplatesareidealforquickwinsduetotheirsimplicity,flexibility,andeaseofcustomization.1)UseacleanlayoutwithBootstrap'sform-groupandform-controlclassesfororganizedandconsistentstyling.2)Customizecolors,sizes,andlayouttofityourbrandbyoverri

What You Need to Know About the Bootstrap Grid System What You Need to Know About the Bootstrap Grid System Jul 13, 2025 am 01:26 AM

BootstrapGridSystemisapowerfultoolforcreatingresponsive,mobile-firstlayouts.1)Itusesa12-columngridwithclasseslike'row'and'col'forstructuringcontent.2)Breakpointslike'col-sm-6'or'col-md-4'allowlayoutstoadapttodifferentscreensizes.3)Nestinggridsandusin

How to install and use Bootstrap Icons library? How to install and use Bootstrap Icons library? Jul 27, 2025 am 01:25 AM

There are three ways to install and use BootstrapIcons: 1. Use CDN and add links to the HTML head; 2. Install through npm, suitable for modern projects such as React and Vue. You need to run npminstallbootstrap-icons and import CSS; 3. Manually download SVG or font files and import them. When using it, you can add bi and icon name classes (such as bi-heart) to insert icons. You can also use other inline elements such as span. It is recommended to use SVG files for better performance and customization capabilities. You can adjust the size through bi-lg, bi-2x and other classes, and use Bootstrap text such as text-danger.

How to Create a Navigation Bar in Bootstrap: A Comprehensive Guide How to Create a Navigation Bar in Bootstrap: A Comprehensive Guide Jul 08, 2025 am 12:29 AM

The steps to create a navigation bar using Bootstrap include: 1. Create an initial navigation bar using the basic navbar component. 2. Customize styles through Bootstrap's utility class and custom CSS. 3. Ensure the navigation bar is responsive on different devices. 4. Add advanced features to the pull-down menu and search bar. 5. Test and optimize the performance and user experience of the navigation bar. With these steps, you can create a powerful and beautiful navigation bar with Bootstrap.

See all articles