'How can I make my dropdown menu close when clicking anywhere on the page (javascript)
I have made a dropdown that opens when the user clicks into the input field, however I want to be able remove the active class so the dropdown disappears when a user clicks anywhere else on the page. Here is my code:
// menu dropdown
const searchInput = document.querySelector('.search-input');
const dropdown = document.querySelector('.dropdown-container');
searchInput.addEventListener('click', () => {
dropdown.classList.add('dropdown-container--active')
})
window.addEventListener('click', function(e) {
if (!searchInput.contains(e.target) && (!dropdown).contains(e.target)) {
dropdown.classList.remove('dropdown-container--active')
}
})
<ul>
<li>
<input data-target="volts" type="text" placeholder="Volts" class="search-input">
<ul class="dropdown-container">
<h5 class="volt-options-title">Top Searches</h5>
<li>
<a href="#" class="volt-options">6</a>
</li>
<li>
<a href="#" class="volt-options">12</a>
</li>
<li>
<a href="#" class="volt-options">24</a>
</li>
<li>
<a href="#" class="last-link">48</a>
</li>
</ul>
</li>
</ul>
Solution 1:[1]
You can make use of the focusout event. Add a listener and remove the active class when the user leaves the search input. As shown below:
searchInput.addEventListener('focusout', (event) => {
dropdown.classList.remove('dropdown-container--active')
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aneesh |
