最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Close modal on esc press (pure JS) - Stack Overflow

programmeradmin1浏览0评论

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):

if (modal.classList.contains('modal-visible')) {
  document.addEventListener('keypress', function(e) {
    let keyCode = e.keyCode;
    if (keyCode === '27') {
      modal.classList.remove('modal-visible');
    }
}

Here's the other code from my JS file for the modal:

const modal = document.getElementById('myModal');
const closeIcon = document.querySelector('.close');

// When called, adds class that sets modal to display: block when player reaches water
function bringUpModal() {
  modal.classList.add('modal-visible');
}

// Closes modal (adding class that sets it back to display: none) upon user's clicking its close icon
closeIcon.addEventListener('click', function() {
  modal.classList.remove('modal-visible');
});

// Opens modal when player reaches water
Player.prototype.update = function(dt) {
    if (this.y === 25) {
        bringUpModal();
        this.y = 400;
    }
};

Doubt this is needed, but just in case, here's my CSS for the modal as well:

.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;
}

.modal-content {
  margin: 0 auto;
  padding: 30px;
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

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):

if (modal.classList.contains('modal-visible')) {
  document.addEventListener('keypress', function(e) {
    let keyCode = e.keyCode;
    if (keyCode === '27') {
      modal.classList.remove('modal-visible');
    }
}

Here's the other code from my JS file for the modal:

const modal = document.getElementById('myModal');
const closeIcon = document.querySelector('.close');

// When called, adds class that sets modal to display: block when player reaches water
function bringUpModal() {
  modal.classList.add('modal-visible');
}

// Closes modal (adding class that sets it back to display: none) upon user's clicking its close icon
closeIcon.addEventListener('click', function() {
  modal.classList.remove('modal-visible');
});

// Opens modal when player reaches water
Player.prototype.update = function(dt) {
    if (this.y === 25) {
        bringUpModal();
        this.y = 400;
    }
};

Doubt this is needed, but just in case, here's my CSS for the modal as well:

.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;
}

.modal-content {
  margin: 0 auto;
  padding: 30px;
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
Share Improve this question asked Jul 11, 2018 at 19:47 nCardotnCardot 6,6258 gold badges56 silver badges100 bronze badges 2
  • 2 Hi Natalie! You don't need the if check in your first code snippet. You want to set up a listener so that anytime the escape key is pressed, the modal-visible class is removed. Also, if the if-check if false, the listener won't be created at all! Finally, check that your parentheses and brackets match in your first code snippet. They look like they're not matched up, which may be why it appears to break your code :) – Andrey Commented Jul 11, 2018 at 19:53
  • 2 if (keyCode === 27) would be better, no? – user1596522 Commented Jul 11, 2018 at 19:58
Add a ment  | 

2 Answers 2

Reset to default 5

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>

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 bees 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'.

发布评论

评论列表(0)

  1. 暂无评论