We can use the onkeyup event to run a function when a user types something into an input field. To do this we can add a function call to the onkeyup event in the HTML.

The onkeyup event is very similar to the onkeydown event, the main difference being that the onkeydown event will fire once a key is pressed, while the onkeyup event will only run once the key is pressed AND released.

This can also be done in jQuery using the keyup() method.

A JavaScript example using the onkeyup event

In this example, we will just have a simple input field with a div below it. When a user enters a key in the input field, we will display what key was pressed below. Here is the HTML setup:

Type any key below


We will use the onkeyup event to run the function below. The function will retrieve the key that was pressed and display that below in the results div using the textContent property.

Here is the JavaScript code:

function keyPressed(e){
  var key = e.key;
  document.getElementById("result").textContent = key;
};

The final code and output for this example of using the onkeyup event is below:

Code Output:

Type any key below

Full Code:

Type any key below



<script>

function keyPressed(e){
  var key = e.key;
  document.getElementById("result").textContent = key;
};

</script>

Hopefully this article has been useful to help you understand how to use the onkeyup event.

Categorized in:

JavaScript,

Last Update: May 3, 2024