Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

Difference between the onkeyup and onkeydown events in Javascript

Chinweuba Elijah Azubuike

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

  • HTML
  • CSS
  • JavaScript
Difference between the onkeyup and onkeydown events

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 the onkeyup event listener using onkeyup="myFunction()". The passed myFunction() is used to execute the code.
  • Line 7: We use an input tag to which we give the id "mySelect2". We also trigger the onkeydown event listener using onkeydown="myFunction2()". The passed myFunction2() is used to execute the code.
  • Line 13: We write the function myFunction which we called in the onkeyup event listener.
  • Line 14: We get the value of the first input field with the onkeyup event by its id.
  • Line 15: We output whatever is entered to the screen.
  • Line 19: We write the function myFunction2 which we called in the onkeydown event listener.
  • Line 20: We get the value of the first input field with the onkeydown event 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 the onkeyup event is output completely, but that controlled by the onkeydown event is missing the last entry. That is why onkeydown shouldn't be used for making calculations in realtime.

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring