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/coreand 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)
How to use Bootstrap forms?
Aug 05, 2025 am 08:34 AM
The key to using Bootstrap forms is to master its structure and use of classes. 1. The basic form structure uses form-control, form-label, form-text and form-check to style input, label, help text and check boxes; 2. Horizontal forms are displayed in line with labels and controls by combining grid systems (such as col-sm-*), and inline forms use practical classes such as d-flex to replace the removed form-inline in Bootstrap5; 3. Form verification uses is-valid or is-invalid classes to match valid-feedback and invalid-feedback to display inversely.
How to use Bootstrap form validation?
Aug 05, 2025 am 05:59 AM
Bootstrapformvalidationusesbuilt-instylestoshowvalid/invalidstateswithvisualfeedback.1.Addnovalidatetodisablebrowsertooltips.2.Useneeds-validationforreal-timefeedbackorwas-validatedaftersubmission.3.IncludeHTML5validationattributeslikerequired.4.Disp
How to create a sticky sidebar on scroll in Bootstrap
Aug 22, 2025 am 09:02 AM
The easiest way to create a sticky sidebar with Bootstrap is to use the built-in sticky-top class with top offset. 1. Add sticky-top class on the sidebar content wrapping element and set style="top:20px;" to avoid overlapping with the head; 2. Make sure that the parent container (such as col-md-3) does not have styles that affect sticky behavior, such as overflow:hidden; 3. Optionally set position:sticky through custom CSS and add height:100vh and overflow-y:auto to support scrolling in the sidebar; 4. If you need to be compatible with old browsers or dynamic controls, you can use
How to customize the Bootstrap navbar toggle
Aug 12, 2025 am 06:57 AM
Tochangethetoggleiconcolor,modifythestrokevalueinthebackground-imageSVGdataURLoruseacustomclasswithanewSVGcolor.2.Resizethetogglebyadjustingthebackground-sizepropertyof.navbar-toggler-iconortweakpaddingandfontsizeforbetterproportions.3.Replacethedefa
How to use Bootstrap with Sass
Aug 18, 2025 am 06:15 AM
Using Bootstrap and Sass requires first installing and configuring the environment, and then efficient development is achieved through variable customization and compilation. 1. Make sure that Node.js is installed, create the project and run npminit-y initialization; 2. Install Bootstrap and DartSass: npminstallbootstrapsass; 3. Create the scss folder and create a new main.scss, first overwrite the Bootstrap variable (such as $primary:#ff6b35;) and then import @import"../node_modules/bootstrap/scss/bootstrap"; 4.
How to create a responsive sidebar with Bootstrap?
Aug 08, 2025 am 03:04 AM
Using Bootstrap5's Offcanvas component and responsive grid system, it is easy to create a responsive sidebar that slides out on a small screen and is fixedly displayed on a large screen; 2. Trigger the offcanvas display menu through the "ToggleSidebar" button on mobile devices, and the medium and above screen sidebars are always visible as col-md-3 columns; 3. Optionally add desktop folding function through JavaScript, combined with CSS media query to achieve click shrink into narrow bars and hide text; 4. It is recommended to use icons to optimize compact views, keep navigation concise, avoid unnecessary fixed positioning, and test the response effect through developer tools, and ultimately achieve a smooth user experience with minimal code.
How to change the default Bootstrap colors
Aug 21, 2025 am 03:10 AM
To change the default color of Bootstrap, the most recommended way is to redefine and recompile via the Sass variable. 1. Create a custom Sass file (such as custom.scss); 2. Overwrite its color variables before importing Bootstrap, such as $primary:#ff6b35; 3. Optionally add custom colors through map-merge to extend the palette; 4. Use the Sass compiler (such as DartSass, Webpack, etc.) to generate customized CSS; 5. If Sass cannot be used, you can use CSS override (requires!important, not recommended) or CSS custom attributes (only partially valid). The correct way is to modify it first
How to use Bootstrap buttons and button groups?
Aug 04, 2025 am 12:18 AM
Bootstrap buttons achieve diversified design by combining btn classes and style classes. 1. Use btn-primary to btn-link and other classes to create different style buttons, combine btn-lg and btn-sm to resize, and use btn-outline-* to create outline buttons; 2. Group buttons horizontally through btn-group containers and add btn-group-vertical to achieve vertical stacking; 3. Apply btn-group-lg or btn-group-sm to unify the size; 4. Nesting dropdown-toggle and dropdown-menu in the button group to implement the dropdown menu, and Boots needs to be introduced


