title: Hide popup box function reverting open popup box function
body: <p>I want to make a "popup" box activated by a button that reduces the opacity of all other elements. When the user clicks out of the box, it should disappear and the opacity should go back to normal. However, these two functions are conflicting with each other. It requires me to click the button TWICE in order for <code>showBox()</code> to be called. And clicking out of the box does nothing unless I reinvoke <code>hideOnClickOutside(document.querySelector('div'));</code> in the browser's console. </p>
  
  <p>Why do I have to click "New Audio" twice and why does <code>hideOnClickOutside()</code> not work unless reinvoked?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function showBox() {
    document.body.style.opacity = "0.5";
    document.querySelector('div').style.display = "block";
  }
  
  document.querySelector('button').addEventListener('click', showBox);
  const isVisible = elem =&gt; !!elem &amp;&amp; !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
  function hideOnClickOutside(element) {
    const outsideClickListener = event =&gt; {
      if (!element.contains(event.target) &amp;&amp; isVisible(element)) { // or use: event.target.closest(selector) === null
        element.style.display = 'none';
        removeClickListener()
        document.body.style.opacity = "1";
      }
    }
  
    const removeClickListener = () =&gt; {
      document.removeEventListener('click', outsideClickListener)
    }
  
    document.addEventListener('click', outsideClickListener)
  }
  
  hideOnClickOutside(document.querySelector('div'));</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button&gt;New Audio&lt;/button&gt;
  
  &lt;div style="display: none"&gt;
    &lt;button&gt;Record Directly&lt;/button&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><code>hideOnClickOutside()</code> function was taken from <a href="https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element/3028037#3028037">another StackOverflow answer</a></p>
  
  <h2>Edit</h2>
  
  <p>I figured out that it requires two clicks because on the first click, <code>showBox()</code> <em>is</em> called, but immediately after, so is outsideClickListener, and at this point the element is NOW visible AND the user has clicked "outside" the element. This reverts the style changes of <code>showBox()</code>. </p>