Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!