Home > Software design >  Keypress function in javascript not working
Keypress function in javascript not working

Time:10-26

addEventListener('keypress', ({keyCode}) => {
    switch(keyCode){
        case 87: //up
            alert('press')
        break;
    }
})

Why is my keypress not working, if I change it to keydown, it works but keypress does not

CodePudding user response:

See the documentation on MDN:

The keypress event is fired when a key that produces a character value is pressed down.

(bold added for emphasis)

The reason it does not work is that the Up key does not produce a character. Try here:

document.addEventListener('keypress', ({keyCode}) => {
  console.log("fired", keyCode);
});
Click here to focus then try pressing a letter key 
and then try something else like up, or backspace, or Alt.

To react to events of other keys use other events such as keydown, or keyup.

Do note that keypress itself is deprecated, MDN has an explicit guidance for that:

Warning: Since this event has been deprecated, you should use beforeinput or keydown instead.

CodePudding user response:

keypress is now deprecated (see documentation here)

You should now either use keydown or keyup

According to the documentation :

The keyup event is fired when a key is released.

The keydown event is fired when a key is pressed.

Example :

const keyupInput = document.getElementById('keyup-button')
const keydownInput = document.getElementById('keydown-button')

keyupInput.addEventListener('keyup', ({key, code}) => {
  console.log('keyup', key, code)
})

keydownInput.addEventListener('keydown', ({key, code}) => {
  console.log('keydown', key, code)
})
<label>keyup</label>
<input id="keyup-button" />

<label>keydown</label>
<input id="keydown-button" />

CodePudding user response:

keypress event is deprecated. Although some browsers still support it, it is not recommended to use. Instead you can use keydown event. MDN Reference

And most importantly it supports of keys that produce a character value are alphabetic, numeric, and punctuation keys. To work with arrow key, you should use keyup or keydown event as your requirement. Here is the example of keydown:

document.addEventListener('keydown', ({keyCode}) => {
  switch(keyCode){
    case 38: //key up in mac
      console.log('pressing key 38');
      alert('press')
    break;
  }
})

  • Related