Home > Back-end >  How can I make my dropdown menu close when clicking anywhere on the page (javascript)
How can I make my dropdown menu close when clicking anywhere on the page (javascript)

Time:05-05

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" >
            <ul >
              <h5 >Top Searches</h5>
                <li>
                  <a href="#" >6</a>
                </li>
                <li>
                  <a href="#" >12</a>
                </li>
                <li>
                  <a href="#" >24</a>
                </li>
                <li>
                  <a href="#" >48</a>
                </li>
            </ul>
          </li>
        </ul>

CodePudding user response:

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')
});

  • Related