Skip to content
Advertisement

Keyup works while keypress doesn’t Vanilla JS

I’m kinda re-learning JS and try to make modal windows in vanilla JS. So, my task is to make Escape button work and close modal on hitting it. I found out that when I put ‘keypress’ event on document, it fails to work, while ‘keyup’ works okay. I couldn’t find exact info on why it is so. I used to use e.KeyCode but found out it is deprecated. So I mainly have 2 questions I couldn’t find direct answers to:

  1. why keycode doesn’t work?

  2. what is the best way to handle keyboard events in 2021?

Here is the code. Console.log doesn’t work. If I change keypress to keyup, everything works.

document.addEventListener('keypress', function (e) {
  console.log('Event fired');
  if (e.key === "Escape" && !modal.classList.contains('hidden')) {
    closeModal();
  }
})

Thanks in advance.

Best regards,

Vadim

Advertisement

Answer

  1. Like you said “keyCode” is deprecated but it still works (see example below).
  2. The best way in your case would be to use keyup and e.key.

Your code works as expected (with any other key), but the keypress event is never fired for Escape. So you can only use keydown and keyup.

document.addEventListener('keypress', function(e) {
  console.log('keypress fired; ', e.key);
})
document.addEventListener('keyup', function(e) {
  console.log('keyup fired; ', e.key);
  if(e.keyCode == '27') alert('Escape');
})
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement