onKeyPress Vs. onKeyUp and onKeyDown
Asked Answered
H

14

488

What is the difference between these three events? Upon googling I found that:

  • The onKeyDown event is triggered when the user presses a key.
  • The onKeyUp event is triggered when the user releases a key.
  • The onKeyPress event is triggered when the user presses & releases a key (onKeyDown followed by onKeyUp).

I understand the first two, but isn't onKeyPress the same as onKeyUp? Is it possible to release a key (onKeyUp) without pressing it (onKeyDown)?

This is a bit confusing, can someone clear this up for me?

Handtomouth answered 3/8, 2010 at 13:10 Comment(3)
I found that if I hold the TAB key down that it continuously cycles through all fields and only triggers 'onkeydown'.Mcbrayer
keypress event represents a character being typed that can be used for input, such as 'a', 'D', '£', '©', and so on. On the other hand, keydown and keyup events represent ANY keys being typed, which includes things like backspace, tab, up, down, home, end, and so on.Ziegler
"(or is it possible to release a key(KeyUp) without pressing(KeyDown) it?)" - Yes. For example, the tab key: the keyup event may not be captured by the same element as the keydown.Getupandgo
P
243

Check here for the archived link originally used in this answer.

From that link:

In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.

Puree answered 3/8, 2010 at 13:15 Comment(8)
Put together a jsfiddle based on @Falk's post to demonstrate the idiosynchracies (using jquery): jsfiddle.net/zG9MF/2Burletta
I can't see the linked page but the point about 'a character being typed' is an important one if you plan on using this for any sort of validation. The keypress event doesn't fire when the user deletes a character, so your validation won't fire.Chaliapin
@Tony Merryfield -Sorry to hear that, but hopefully the citation in the answer was helpful to you. You are correct that keypress doesn't fire when delete key is pressed, because it is trapping the event where a character is actually typed.Puree
@Puree - Yes, was enough of a hint to get me on the right path. I just added my comment to reinforce the point that the event only triggers when a character is typed as opposed to any keypress - you got my upvote ;)Chaliapin
Also, on a "long" press of a key, the KeyDown event keeps firing until the key is released in which case KeyUp is fired only once ;)Debora
A more useful statement from the article you cited: "The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released."Lingua
keypress cannot detect esc, tab, enter keys. :)Blanchard
keypress is deprecated developer.cdn.mozilla.net/en-US/docs/Web/API/Element/…Aftonag
C
327

NOTE KeyPress is now deprecated. Use KeyDown instead.

KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

The exception is webkit, which has an extra event in there:

keydown
keypress
textInput     
keyup

Below is a snippet you can use to see for yourself when the events get fired:

window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);

function log(event){
  console.log( event.type );
}
Catabasis answered 3/8, 2010 at 13:16 Comment(10)
So, Is KeyPress just an extra event that's b/w KeyDown and TextInput? How is it(KeyPress) generally used by developers?Handtomouth
+1 best answer - The *Down happens first, the *Press happens second (when text is entered), and the *Up happens last (when text input is complete).Threedecker
-1 because a little experimentation in the snippet contradicts your analogy to the 'click' event. The 'click' event fires at the same time as 'mouseup' (when you release the mouse button), but the 'keypress' event fires at the same time as 'keydown' (when the key is first depressed).Digamma
@MarkAmery: keypress doesn't fire at the same time keydown does. If it ever appears to happen at the same time it's because your timer doesn't resolve events shorter than milliseconds. But the sequence is still preserved.Catabasis
@Catabasis Actually, the keypress and keydown events literally get assigned the same .timeStamp value, which is accurate to intervals of 5 microseconds, but that's not really my point anyway. My point is that the click event doesn't fire until you release the mouse button, so saying that keypress is the keyboard version of click makes it sound like keypress will likewise not fire until you release the key. In fact, that's not the case: it fires when the key is depressed, just like keydown does. So keypress isn't in fact analogous to click at all.Digamma
@Mark: In fact, whatever your point is, how do you explain the 'keypress' always being recorded after the 'keydown'? It looks like you just want to have an argument for argument's sake.Catabasis
@Catabasis "how do you explain the 'keypress' always being recorded after the 'keydown'" - simple: the same user action (pushing down a key) immediately triggers both handlers to be pushed into the event queue, but in a fixed order. "you just want to have an argument for argument's sake" - Eh? The core thesis of your answer is that keypress, keyup, and keydown are analogous to click, mouseup, and mousedown. The natural interpretation of that, to me, is that keypress fires at the same instant as keyup (just like click and mouseup). What did you mean, if not that?Digamma
What is natural to you is not necessarily natural. My original answer to the question states that keydown happens first and keypress happens second. You have not refuted that. In fact, you just confirmed it by calling it a "fixed order." But if you just want to argue to hear yourself talk, knock yourself out. The rest of us have work to do.Catabasis
keypress is deprecated developer.cdn.mozilla.net/en-US/docs/Web/API/Element/…Aftonag
for mouse events: down then up, then if they're on the same element, click.Finale
P
243

Check here for the archived link originally used in this answer.

From that link:

In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.

Puree answered 3/8, 2010 at 13:15 Comment(8)
Put together a jsfiddle based on @Falk's post to demonstrate the idiosynchracies (using jquery): jsfiddle.net/zG9MF/2Burletta
I can't see the linked page but the point about 'a character being typed' is an important one if you plan on using this for any sort of validation. The keypress event doesn't fire when the user deletes a character, so your validation won't fire.Chaliapin
@Tony Merryfield -Sorry to hear that, but hopefully the citation in the answer was helpful to you. You are correct that keypress doesn't fire when delete key is pressed, because it is trapping the event where a character is actually typed.Puree
@Puree - Yes, was enough of a hint to get me on the right path. I just added my comment to reinforce the point that the event only triggers when a character is typed as opposed to any keypress - you got my upvote ;)Chaliapin
Also, on a "long" press of a key, the KeyDown event keeps firing until the key is released in which case KeyUp is fired only once ;)Debora
A more useful statement from the article you cited: "The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released."Lingua
keypress cannot detect esc, tab, enter keys. :)Blanchard
keypress is deprecated developer.cdn.mozilla.net/en-US/docs/Web/API/Element/…Aftonag
S
50

Most of the answers here are focused more on theory than practical matters and there's some big differences between keyup and keypress as it pertains to input field values, at least in Firefox (tested in 43).

If the user types 1 into an empty input element:

  1. The value of the input element will be an empty string (old value) inside the keypress handler

  2. The value of the input element will be 1 (new value) inside the keyup handler.

This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.

Scenario:

  1. The user types 12345 into an input element.
  2. The user selects the text 12345.
  3. The user types the letter A.

When the keypress event fires after entering the letter A, the text box now contains only the letter A.

But:

  1. Field.val() is 12345.
  2. $Field.val().length is 5
  3. The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).

So it seems that the browser (Firefox 43) erases the user's selection, then fires the keypress event, then updates the fields contents, then fires keyup.

Sulk answered 4/2, 2017 at 5:45 Comment(0)
I
32

First, they have different meaning: they fire:

  • KeyDown – when a key was pushed down
  • KeyUp – when a pushed button was released, and after the value of input/textarea is updated (the only one among these)
  • KeyPress – between those and doesn't actually mean a key was pushed and released (see below). Not only it has inconsistent semantics, it was deprecated, so one shouldn't probably use it (see also this summary)

Second, some keys fire some of these events and don't fire others. For instance,

  • KeyPress ignores delete, arrows, PgUp/PgDn, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don't (see details about esc below);
  • when you switch window via alt+tab in Windows, only KeyDown for alt fires because window switching happens before any other event (and KeyDown for tab is prevented by system, I suppose, at least in Chrome 71).

Also, you should keep in mind that event.keyCode (and event.which) usually have same value for KeyDown and KeyUp but different one for KeyPress. Try the playground I've created. By the way, I've noticed quite a quirk: in Chrome, when I press ctrl+a and the input/textarea is empty, for KeyPress fires with event.keyCode (and event.which) equal to 1! (when the input is not empty, it doesn't fire at all).

Note: these days, using event.key and event.code are the most useful options as it is standardized across browsers, OSes and events (afaik), while event.which and event.keyCode are deprecated (1, 2).

Finally, there's some pragmatics:

  • For handling arrows, you'll probably need to use onKeyDown: if user holds , KeyDown fires several times (while KeyUp fires only once when they release the button). Also, in some cases you can easily prevent propagation of KeyDown but can't (or can't that easily) prevent propagation of KeyUp (for instance, if you want to submit on enter without adding newline to the text field).
  • Suprisingly, when you hold a key, say in textarea, both KeyPress and KeyDown fire multiple times (Chrome 71), I'd use KeyDown if I need the event that fires multiple times and KeyUp for single key release.
  • KeyDown is usually better for games when you have to provide better responsiveness to their actions.
  • esc is usually processed via KeyDown: KeyPress doesn't fire and KeyUp behaves differently for inputs and textareas in different browsers (mostly due to loss of focus)
  • If you'd like to adjust height of a text area to the content, you probably won't use onKeyDown but rather onKeyPress (PS ok, it's actually better to use onChange for this case).

I've used all 3 in my project but unfortunately may have forgotten some of pragmatics. (to be noted: there's also input and change events)

Impressionable answered 9/3, 2016 at 14:14 Comment(1)
I hadn't thought about keyup adding the newline to the field contents, but that's actually important.Beg
M
22

onkeydown is fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrl is held 'down'.

onkeyup is fired when the key is released (including modifier/etc keys)

onkeypress is fired as a combination of onkeydown and onkeyup, or depending on keyboard repeat (when onkeyup isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)

textInput (webkit only) is fired when some text is entered (for example, Shift+A would enter uppercase 'A', but Ctrl+A would select text and not enter any text input. In that case, all other events are fired)

Mining answered 21/7, 2011 at 10:44 Comment(1)
Just confirmed that, indeed, "onkeypress" is called repeatedly when the key is held down, and "keyboard repeat" occurs. However, this is also true for "onkeydown"! (which is unexpected, given the name)Amperage
O
14

This article by Jan Wolter is the best piece I have came across, you can find the archived copy here if link is dead.

It explains all browser key events really well,

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

To understand the difference between keydown and keypress, it is useful to distinguish between characters and keys. A key is a physical button on the computer's keyboard. A character is a symbol typed by pressing a button. On a US keyboard, hitting the 4 key while holding down the Shift key typically produces a "dollar sign" character. This is not necessarily the case on every keyboard in the world. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. In practice, this is not always the way it is implemented.

For a while, some browers fired an additional event, called textInput, immediately after keypress. Early versions of the DOM 3 standard intended this as a replacement for the keypress event, but the whole notion was later revoked. Webkit supported this between versions 525 and 533, and I'm told IE supported it, but I never detected that, possibly because Webkit required it to be called textInput while IE called it textinput.

There is also an event called input, supported by all browsers, which is fired just after a change is made to to a textarea or input field. Typically keypress will fire, then the typed character will appear in the text area, then input will fire. The input event doesn't actually give any information about what key was typed - you'd have to inspect the textbox to figure it out what changed - so we don't really consider it a key event and don't really document it here. Though it was originally defined only for textareas and input boxes, I believe there is some movement toward generalizing it to fire on other types of objects as well.

Oao answered 31/8, 2017 at 10:42 Comment(1)
Best answer, so how can you get, say, the dollar sign symbol from keypress?Scrap
I
11

Updated Answer:

KeyDown

  • Fires multiple times when you hold keys down.
  • Fires meta key.

KeyPress

  • Fires multiple times when you hold keys down.
  • Does not fire meta keys.

KeyUp

  • Fires once at the end when you release key.
  • Fires meta key.

This is the behavior in both addEventListener and jQuery.

https://jsbin.com/vebaholamu/1/edit?js,console,output <-- try example

shows example with holding down for SSS

(answer has been edited with correct response, screenshot & example)

Iaria answered 28/6, 2018 at 1:25 Comment(4)
Except for keydown that fires multiple times alsoScrap
-1, because at least one detail on this is wrong in at least Chrome; as @bluejayke says, KeyDown also fires repeatedly when you hold down a key.Digamma
Yeah you guys are right, sorry for my mistake; answer edited.Iaria
keypress fires for every added character, while keydown fires constantly (magnitute more times in the same amount of time depending on repeat speed)Chancelor
D
10

It seems that onkeypress and onkeydown do the same (whithin the small difference of shortcut keys already mentioned above).

You can try this:

<textarea type="text" onkeypress="this.value=this.value + 'onkeypress '"></textarea>
<textarea type="text" onkeydown="this.value=this.value + 'onkeydown '" ></textarea>
<textarea type="text" onkeyup="this.value=this.value + 'onkeyup '" ></textarea>

And you will see that the events onkeypress and onkeydown are both triggered while the key is pressed and not when the key is pressed.

The difference is that the event is triggered not once but many times (as long as you hold the key pressed). Be aware of that and handle them accordingly.

Dagger answered 27/5, 2012 at 21:10 Comment(1)
Ctrl, Shift, CapsLock, Backspace and other keys that do not type something do not cause a keypress event, but they always trigger a keydown.Blackboard
M
9

The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.

Meuser answered 4/8, 2014 at 8:14 Comment(1)
keypress also ignores delete, arrows, home/end, PgUp/PgDn, see my answer for details (you may want to update your answer too)Impressionable
B
4

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

Betsybetta answered 19/12, 2017 at 12:5 Comment(2)
It appears that things are the same for Numeric Character (0123456789)Alberic
And did you notice that keyDown gives the KEY on the keyboard, while keyPress gives the exact Character we just typed (or clicked)Alberic
B
2

Basically, these events act differently on different browser type and version, I created a little jsBin test and you can check the console for find out how these events behavior for your targeted environment, hope this help. http://jsbin.com/zipivadu/10/edit

Betimes answered 24/2, 2014 at 16:26 Comment(0)
P
1

BLAZOR....

If you want to check which key is pressed use onkeypress OR onkeydown but if you want to get the text from the text field and then check the last key pressed for example you are scanning a barcode and you want to fire an even when the ENTER key is pressed (almost all barcode scanners send 13 "ENTER" in the last) then you should use onkeyup otherwise you will not get the text typed in the text field.

For example

<input type="text" class="form-control" @bind="@barcode" @onkeyup="BarCodeScan" placeholder="Scan" />

This will call the BarCodeScan function immediately after you will press enter by typing the code or if you scan it from scanner the BarCodeScan function will be called automatically. If you will use "onkeypress" or "onkeydown" here then the bind will not take place and you will not get the text from the text field.

Pratte answered 8/5, 2021 at 19:24 Comment(2)
Microsoft Blazor Server and WebAssembly apps ... (ASP .NET core)Pratte
Ah. You might revise your answer to make that more clear. There's no mention of it on this page until then.Guilder
W
1

The difference which I observed between keyup and keydown is

if we attach a eventhandler for keydown event and log the input box value i.e (e.target.value) it returns whatever the value was before keydown event

But if we attach a eventhandler for keyup event and log the input box value it returns the latest value including the key which was pressed

LETS UNDERSTAND WITH EXAMPLE


// the latest keypressed is not shown in e.target.value
// when keydown event handler is executed
// since until the keyup is not triggered 
// the input box will not have that character in its value
const searchCitiesEleKeyDown = document.querySelector("#searchCities");
searchCitiesEleKeyDown.addEventListener("keydown", (e) => {
  console.log(e.target.value);
});


// but in case of keyup event the e.target.value prints 
// the text box content with the latest character pressed
// since as soon as the keyup event triggers
// the input box will have that character pressed in its value
const searchCitiesEleKeyUp = document.querySelector("#searchCities");
searchCitiesEleKeyUp.addEventListener("keyup", (e) => {
  console.log(e.target.value);
});
<input type="text" id="searchCities" />

CodeSandbox Link https://codesandbox.io/s/keydown-vs-keyup-wpj33m

Wine answered 24/4, 2022 at 12:36 Comment(0)
B
0

A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):

$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>

Pressing:

  • non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:

    keydown 17 17 Control

    keyup 17 17 Control

  • keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:

    keydown 192 192 Dead

    keydown 192 192 ´´

    keypress 180 180 ´

    keypress 180 180 ´

    keyup 192 192 Dead

Additionally, non typing inputs (e.g. ranged <input type="range">) will still trigger all keyup, keydown and keypress events according to the pressed keys.

Blackboard answered 13/9, 2019 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.