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

214
Views
How do I close a dropdown menu when I click outside the dropdown

When I press into the dropdown field itself, it should stay open

If I click outside the dropdown, it should be closed.

When open, page (hover effects, tooltips, ...) should continue to work.

.dropdown {
  position: relative;
  &__window {
    position: absolute;
    background: $background-alt;
    width: 100%;
    z-index: 12;
    overflow: hidden;
    display: none;
    visibility: hidden;
    &--active {
      display: block;
      visibility: visible;
    }
    > * {
      width: 100%;
      white-space: nowrap;
    }
  }
}
let dropdownBtn = document.querySelectorAll('.dropdown__open')
let dropdownWindows = document.querySelectorAll('.dropdown__window')

dropdownBtn.forEach((el) => {
  el.addEventListener('click', (e) => {
    e.target.nextElementSibling.classList.toggle('dropdown__window--active')
  })
})
    <div class="dropdown">
      <button class="dropdown dropdown__open">Open Dropdown</button>
      <div class="dropdown__window">
        <a>Link Text</a>
        <a>Link Text</a>
        <a>Link Text</a>
        <a>Link Text</a>
      </div>
    </div>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

let dropdownBtn = document.querySelectorAll('.dropdown__open');
let dropdownWindows = document.querySelectorAll('.dropdown__window');

dropdownBtn.forEach((el) => {
  el.addEventListener('click', (e) => {
    // toggle class
    e.target.nextElementSibling.classList.toggle('dropdown__window--active');
    const listener = (evt) => {
      // toggle class back, use old event target
      e.target.nextElementSibling.classList.toggle('dropdown__window--active');
      evt.preventDefault();
      evt.stopPropagation();
      listener();
      // remove listener once clicked
      window.removeEventListener(listener);
    };
    // create global handler for "click off" 
    window.addEventListener('click', listener);
  });
});
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!