How do I close dropdowns on click outside when using custom JS?
Asked on Sep 01, 2025
1 Answer
To close dropdowns when clicking outside of them using custom JavaScript, you can add an event listener to the document that checks if the click target is outside the dropdown. If it is, you manually hide the dropdown.
<!-- BEGIN COPY / PASTE -->
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</div>
<script>
document.addEventListener('click', function(event) {
var dropdown = document.querySelector('.dropdown');
var isClickInside = dropdown.contains(event.target);
if (!isClickInside) {
var dropdownMenu = dropdown.querySelector('.dropdown-menu');
if (dropdownMenu.classList.contains('show')) {
bootstrap.Dropdown.getInstance(dropdownMenu).hide();
}
}
});
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- The code uses Bootstrap's JavaScript API to hide the dropdown.
- The `document.addEventListener('click', ...)` listens for clicks anywhere on the page.
- `dropdown.contains(event.target)` checks if the click was inside the dropdown.
- If the click is outside, it hides the dropdown using Bootstrap's `Dropdown.getInstance().hide()` method.
- Ensure that Bootstrap's JavaScript is properly included in your project for this to work.