Difference between the onkeyup and onkeydown events in Javascript
Overview
The onkeyup and onkeydown are events triggered by users whenever they try to communicate with a web application. In this shot, we will look at the difference between the onkeyup and the onkeydown events. These events are related closely but they are triggered differently.
Usage
We use the two event listeners to communicate with our web application. This involves entering information in a particular section of the web application. The event listeners are normally attached directly to an HTML element where the action will be triggered or the HTML element is selected by id,class or tag.
Syntax of onkeyup
onkeyup() is used when selecting the tag via id, class, or tag.
onkeyup="function" // is used when attached directly to an HTML tag.
Parameter of onkeyup
onkeyup recieves a code snippet or a function to execute.
Syntax of onkeydown
onkeydown() is used when selecting the tag via id, class, or tag.
onkeydown="function" // is used when attached directly to an HTML tag.
Parameter of onkeydown
onkeydown receives a code snippet or a function to execute.
Let's see a practical example to demonstrate the difference between the two event listeners.
Code
Explanation
In the code above, we can see the difference between the two event listeners.
- Line 6: We use an input tag to which we give the id
"mySelect". We also trigger theonkeyupevent listener usingonkeyup="myFunction()". The passedmyFunction()is used to execute the code.
- Line 7: We use an input tag to which we give the id
"mySelect2". We also trigger theonkeydownevent listener usingonkeydown="myFunction2()". The passedmyFunction2()is used to execute the code.
- Line 13: We write the function
myFunctionwhich we called in theonkeyupevent listener.
- Line 14: We get the value of the first input field with the
onkeyupevent by its id.
- Line 15: We output whatever is entered to the screen.
- Line 19: We write the function
myFunction2which we called in theonkeydownevent listener.
- Line 20: We get the value of the first input field with the
onkeydownevent by its id.
- Line 21: We output whatever is entered to the screen.
Difference
Observe how everything we enter in the field that is controlled by theonkeyupevent is output completely, but that controlled by theonkeydownevent is missing the last entry. That is whyonkeydownshouldn't be used for making calculations in realtime.