Languages
[Edit]
EN

JavaScript - Keyboard Events

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you keyboard events and the differences between them in JavaScript.

Quick solution:

<input type="text" onkeydown="functionName()">
<input type="text" onkeypress="functionName()">
<input type="text" onkeyup="functionName()">

 

Introduction

There are three keyboard events in JavaScript that describe user interaction with the keyboard:

  • onkeydown
  • onkeypress
  • onkeyup

1. onkeydown event

The event occurs when the user is pressing a key on the keyboard.

Practical example

In this example, we will execute myFunction() on key down event inside the input field.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something:</p>
    <input type="text" 
           onkeydown="myFunction()"/>
    <script>
      function myFunction(){
        console.log('onkeydown');
      }
    </script>
  </body>
</html>

2. onkeypress event

The event occurs when the user presses a key (when a character is being typed).

Practical example

In this example, we will execute myFunction() on key press event inside the input field.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something:</p>
    <input type="text"
           onkeypress="myFunction()"/>
    <script>
        function myFunction(){
        console.log('onkeypress');
      }
    </script>
  </body>
</html>

3. onkeyup event

The event occurs when the user releases a key on the keyboard.

Practical example

In this example, we will execute myFunction() on key up event inside the input field.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something:</p>
    <input type="text" 
           onkeyup="myFunction()"/>
    <script>
        function myFunction(){
        console.log('onkeyup');
      }
    </script>
  </body>
</html>

Differences

The main difference is the order in which the events occur. You can see it in the example below.

The order of keyboard events:

  1. onkeydown
  2. onkeypress
  3. onkeyup

Runnable example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something:</p>
    <input type="text" 
           onkeydown="handleKeyDown()"  
           onkeypress="handleKeyPress()" 
           onkeyup="handleKeyUp()"/>
    <script>
      function handleKeyDown(){
        console.log('onkeydown');
      }
        function handleKeyPress(){
        console.log('onkeypress');
      }
        function handleKeyUp(){
        console.log('onkeyup');
      }
    </script>
  </body>
</html>

JavaScript - events

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join