title: Close modal when clicking outside of it
body: <p>I was able to make my modal close when clicking on the x icon and when pressing the escape button. How can I also make it close when clicking outside the modal (i.e. the page's body?) Thanks</p>
  <pre><code>document.querySelectorAll(&quot;.modal-trigger&quot;).forEach((trigger) =&gt; {
      const modal = document.querySelector(trigger.dataset.modal);
      const closeBtn = modal.querySelector(&quot;.modal-close&quot;);
      function open() {
          modal.classList.add(&quot;show-modal&quot;);
          trigger.blur();
          document.body.style.overflow = &quot;hidden&quot;;
          document.body.addEventListener(&quot;keydown&quot;, escapeClose);
      }
      function close() {
          modal.classList.remove(&quot;show-modal&quot;);
          document.body.style.overflow = &quot;auto&quot;;
          document.body.removeEventListener(&quot;keydown&quot;, escapeClose);
      }
      function escapeClose(event) {
          if (event.keyCode === 27) {
              close();
          }
      }
      trigger.addEventListener(&quot;click&quot;, open);
      closeBtn.addEventListener(&quot;click&quot;, close);
  });
  </code></pre>