Skip to content Skip to sidebar Skip to footer

Close Modal On Esc Press (pure JS)

I'm trying to get my modal to close (have a class that sets it to display: block removed) on an esc press. Here's what I tried (which doesn't work and breaks the rest of my code):

Solution 1:

Add an event listener for the modal when the page loads, not if the modal is visible. Also, use the keydown event instead of keypress as in some browsers the keypress event is only fired if the key outputs a character

.modal {
  display: none;
  width: 33%;
  height: 30%;
  margin: 0 auto;
  background-color: #f1f0f0;
  border: 1px solid #c5c4c4;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* Added by function bringUpModal() */
.modal-visible {
  display: block;
}
<div id="modal" class="modal modal-visible" style="border: 2px solid black; width: 100px; height: 100px;"></div>
<script>
var modal = document.getElementById("modal");
document.addEventListener('keydown', function(e) {
    let keyCode = e.keyCode;
    document.getElementById("result").innerHTML = "Key Code: "+keyCode+"<br/> Key: "+e.key+"<br/>";
    if (keyCode === 27) {//keycode is an Integer, not a String
      modal.classList.remove('modal-visible');
      document.getElementById("result").innerHTML += "Escape key pressed. Modal hidden.";
    }
});
</script>
<div style="width: 100%; text-align: center;">
 <span id="result"></span>
</div>

Solution 2:

If you only create the event listener if the modal is visible, it will simply never be created. Making the modal visible afterward will not re-execute your code. The if check has already occurred, already failed, and the event listener for keydown has already not been created. At no point will it be created.

var x = 2;
if (x === 1) {
  alert('yes');
}
x = 1;

In the above example, the alert never happens, even though x eventually becomes 1. Similarly, your event listener never gets created.

At the same time, the keyCode is an integer, not a string. You will want to use 27 instead of '27'.


Post a Comment for "Close Modal On Esc Press (pure JS)"