title: Close Dropdown Menu when clicking outside
body: <p>The dropdown menu should open when the button is clicked.</p>
  <p>And if you click outside the dropdown it should close again.</p>
  <p>I tried this by adding an event listener to the body when the dropdown menu is active and then checking if the click happened outside the dropdown.</p>
  <p>How can I write the following code without timeout function and make the dropdown close when clicked <strong>outside</strong> and not inside?</p>
  <pre><code>    &lt;div class=&quot;dropdown dropdown__open&quot;&gt;
        Open Dropdown
  
        &lt;div class=&quot;dropdown__window&quot;&gt;
          &lt;a class=&quot;dropdown__link&quot;&gt;Link Text&lt;/a&gt;
          &lt;a class=&quot;dropdown__link&quot;&gt;Link Text&lt;/a&gt;
          &lt;a class=&quot;dropdown__link&quot;&gt;Link Text&lt;/a&gt;
          &lt;a class=&quot;dropdown__link&quot;&gt;Link Text&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  <pre><code>.dropdown {
    position: relative;
    cursor: pointer;
    user-select: none;
    &amp;__window {
      position: absolute;
      background: $background-alt;
      width: 100%;
      max-width: 260px;
      top: 45px;
      z-index: 12;
      overflow: hidden;
      display: none;
      visibility: hidden;
      &amp;--active {
        display: block;
        visibility: visible;
      }
      &gt; * {
        width: 100%;
        display: block;
        color: $white;
        white-space: nowrap;
        &amp;:hover {
          background: $background;
          color: currentColor;
        }
      }
    }
  }
  </code></pre>
  <pre><code>let dropdownBtn = document.querySelectorAll('.dropdown__open')
  
  dropdownBtn.forEach((el) =&gt; {
    let dropdownWindow = el.querySelector('.dropdown__window')
  
    el.addEventListener('click', function () {
      dropdownWindow.classList.toggle('dropdown__window--active')
  
      window.setTimeout(function () {
        if (dropdownWindow.classList.contains('dropdown__window--active')) {
          let clickListener = document.body.addEventListener(
            'click',
            function (event) {
              if (event.target.classList != 'dropdown__link') {
                dropdownWindow.classList.remove('dropdown__window--active')
                // Buggy clickListener.removeEventListener()
              }
            }
          )
        }
      }, 1000)
    })
  })
  </code></pre>
  <p>OR
  <a href="https://codepen.io/Salala2/pen/RwxjOzW" rel="nofollow noreferrer">https://codepen.io/Salala2/pen/RwxjOzW</a></p>