DEV Community

Cover image for Character not returning on keydown event
Sara Ounissi
Sara Ounissi

Posted on • Originally published at

Character not returning on keydown event

To develop a feature in JavaScript, I started by looking into the events related to the keyboard. I found three events : keypress, keydown, keyup.

keypress was only happening when the user pressed a char key, and I also needed to get the event when the user uses the supr button. So I thought I would use keydown instead.

The event was fired when I pressed any key, however, the problem I faced is that when I pressed down on char key I needed to get that char and save it in a variable. I noticed that the first char was only saved at the second time the event was fired, the second char at the third event and so on. I couldn’t understand this gap.

After some debugging and talking about that with a colleague, I understood that the event keydown was happening too early, it was fired before the char get saved in my variable. So instead of using keydown I used keyup, and it worked perfectly fine.


- keypress : The keypress event is fired when a key that produces a character value is pressed down (Deprecated)
- keydown : The keydown event is fired when any key is pressed down, the event occur very soon.
- keyup : The keyup event is fired when any key is pressed up, the event occur after keydown.

Top comments (0)