onkeydown and onkeyup in Javascript
What are onkeydown and onkeyup?
-
onkeydown: An event in Javascript that occurs when a user presses down a key.
- onkeyup: An event in Javascript that occurs when a user releases a key.
Examples
Example 1:
What's going on here?
-
HTML allows for the input tag, which allows the user to enter certain types of data.
-
The element that Example 1 uses, "text," enters a text box onto a webpage. It looks like this:
-
"id" will be used to call the tag in Javascript later, using getElementbyId.
- When a user presses a key down, the text box's background turns purple. This is the onkeydown event in action.
-
The onkeydown event is described in a function via getElementbyId in Javascript, which looks like this:
-
However, to merely describe the event in a function is not enough. The function itself must be called. When the function is called, it looks like this:
- When a user releases a key, the text box's background turns pink. This is the onkeyup event in action. It is written in the same fashion as onkeydown:
- FULL CODE
Example 2:
What's going on here?
-
The onkeydown and onkeyup events are still being used within the confines of a text box. However, this time, the text box's borders are being targeted, not the text box's background color. We can see this changes inside the "down" and "up" functions:
- The callings of the functions also look identical to the first example:
- FULL CODE
Example 3:
What's going on here?
-
Instead of using a "text" element, the type of input element being used here is called "password," because it masks the characters that the user is typing. In HTML, it looks like this:
- Now, onkeydown and onkeyup functions are targeting the password box's width and height. The up and down functions also look different; they are calling more than one action per event. Notice, however, that the callings of the functions are still the same as the first two examples:
- FULL CODE
More Resources:
-
W3 Schools: onkeyup
- W3 Schools: onkeydown
- W3 Schools: Input Types