JavaScript keycode events | keydown, keypress and keyup

Browsers have client-side events triggered when a keyboard key is pressed or released:

  1. keydown event
  2. keypress event
  3. keyup event

The keydown event occurs when the keyboard key is pressed, and it is followed at once by the execution of keypress event.
The keyup event is generated when the key is released.

JavaScript keycode events Example

HTML example code using onkeypress and onkeydown to demonstrate the differences between character codes and keyboard codes:

<!DOCTYPE html>
<html>
<body>

 <input type="text" onkeypress="uniCharCode(event)" onkeydown="uniKeyCode(event)">


 <script>

  function uniCharCode(event) {
    var char = event.which || event.keyCode;
    console.log("Unicode CHARACTER code: " + char);
  }

  function uniKeyCode(event) {
    var key = event.keyCode;
    console.log("Unicode KEY code: " + key);
  }
</script>

</body>
</html>

Output: Not using caps lock result will be deferent.

JavaScript keycode events

List of char of the JS KeyCodes

Keyboard key PressedJavaScript Key Code value
backspace8
tab9
enter13
shift16
ctrl17
alt18
pause/break19
caps lock20
escape27
page up33
Space32
page down34
end35
home36
arrow left37
arrow up38
arrow right39
arrow down40
print screen44
insert45
delete46
048
149
250
351
452
553
654
755
856
957
a65
b66
c67
d68
e69
f70
g71
h72
i73
j74
k75
l76
m77
n78
o79
p80
q81
r82
s83
t84
u85
v86
w87
x88
y89
z90
left window key91
right window key92
select key93
numpad 096
numpad 197
numpad 298
numpad 399
numpad 4100
numpad 5101
numpad 6102
numpad 7103
numpad 8104
numpad 9105
multiply106
add107
subtract109
decimal point110
divide111
f1112
f2113
f3114
f4115
f5116
f6117
f7118
f8119
f9120
f10121
f11122
f12123
num lock144
scroll lock145
My Computer (multimedia keyboard)182
My Calculator (multimedia keyboard)183
semi-colon186
equal sign187
comma188
dash189
period190
forward slash191
open bracket219
back slash220
close braket221
single quote222

Do comment if you have any doubts and suggestions on this JS keycode topic,

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.