Prevent modal from closing when click didn't initiate outside of content?

Before you answer yourself with a valid cause (as noted in your Question Edit) - take in consideration:

  • onmousedown might not always be the desired UX. (Sometimes experienced users to undo a mousedown not being registered as a click they on purpose move the mouse over another element for the mouseup event just to retain the current state.)
  • Remove inline JavaScript
  • Assign listeners using Element.addEventListener() to any button having the data-modal attribute
  • Use data-modal="#some_modal_id" even no the container element
  • Finally: use if (evt.target !== this) return;

const el_dataModal = document.querySelectorAll('[data-modal]');

function toggleModal(evt) {
  if (evt.target !== this) return; // Do nothing if the element that propagated the event is not the `this` button which has the event attached.
  const id = evt.currentTarget.getAttribute('data-modal');
  document.querySelector(id).classList.toggle('active');
}

el_dataModal.forEach(el => el.addEventListener('click', toggleModal));
html, body {
  margin: 0;
  height: 100%;
}
.modal-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  background-color: rgba(0, 0, 0, 0.75);
  opacity: 0; /* ADDED */
  transition: 0.26s; /* ADDED */
  visibility: hidden; /* ADDED */
}
.modal-container.active {
  opacity: 1; /* ADDED */
  visibility: visible; /* ADDED */
}
.modal-content {
  height: 50%;
  width: 50%;
  margin: auto;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
<button data-modal="#modal-container">Open the Modal</button>

<div id="modal-container" class="modal-container" data-modal="#modal-container">
  <div class="modal-content">
    <input type="text">
    <br><br>
    <button data-modal="#modal-container">CLOSE MODAL TEST</button>
  </div>
</div>

Tags:

Javascript