Bootstrap navbar dropdown not closing on item select
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.
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.

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.

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.

2. Add manual closing logic (recommended method)
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('.dropdown-item').forEach(item => { item.addEventListener('click', () => { const dropdown = bootstrap.Dropdown.getInstance(item.closest('.dropdown-toggle')); 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('.dropdown-item').addEventListener('click', 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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).

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

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

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

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

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

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.

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.
