'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>


Solution 1:[1]

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

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