0

I understand that in Javascript, the 'keypress' event fires when a character gets inserted into the screen and the 'input' event fires when the input field of yours changes. I've seen many good explanations of the different types of events like here, but I was more wondering about the difference between those two events since they seem so similar. Specifically:

  • What, if at all, is the difference between keypress and input events? In my quick testing, it seems like keypress happens first, but is that it?
  • Under what circumstances would I use one over the other?
Daniel
  • 301
  • 4
  • 13
  • keypress is not always leads to input, some buttons do not produce visible characters (like alt) – Iłya Bursov Jun 05 '19 at 20:24
  • 1
    [The `keypress` event is deprecated](https://stackoverflow.com/q/52882144/215552), for one difference. – Heretic Monkey Jun 05 '19 at 20:45
  • The [documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) describes exactly what those events do and it is very easy to see the differences from even just the first sentence. – Herohtar Jun 05 '19 at 20:53

2 Answers2

1

So actually those two events are not the same at all. Let me break it down for you.

  • keypress event triggers when any of your keyboard keys are pressed independently of the element you are focusing. If you press a key on a blank html page, the event will be triggered. This event is mostly used to trigger events like when there is a popup and you press escape, it hides it.
  • input event is specific to the case where you are currently typing or pressing keys while focusing an input element. With it, you can actually get the input value and do stuff with it like in a form, check if the password has symbols, a caps letter, and numbers.

This is the difference between those two events. They don't have the same use at all.

Jaro
  • 1,587
  • 5
  • 20
  • 39
  • As a side note, it's always best to use keypressup instead of keypressdown if you're using that as an event listener, because a user can hold down a key indefinitely which will cause the event listener to fire repeatedly :) – Rich Jun 05 '19 at 20:30
  • True although it depends on the use case. Keypressdown can have its uses if you actually need to repeat an action while the key is pressed. – Jaro Jun 05 '19 at 20:32
  • 2
    @Rich Are you talking about `keyup` and `keydown`? Because there is no `keypressup` or `keypressdown` events, AFAIK. – Heretic Monkey Jun 05 '19 at 20:48
  • Yes, my bad. It's been a long day :) – Rich Jun 05 '19 at 20:52
1

To answer your question about when you would use keyDown or keyUp versus input:

  1. Navigation controls for games
  2. Keys that don't change the text. For instance, using keyDown to detect 'esc' or 'F1' pressed. I commonly use keyDown detection of 'esc' to close popup windows
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80