onkeypress

The onkeypress event in HTML is activated when a key is pressed and released, enabling developers to capture character input for interactive features or actions.

onkeypress event

The onkeypress event attribute is triggered when a key is pressed and released. It can be used to capture user input and respond appropriately in web applications.

The onkeypress event is deprecated and may not work consistently across different browsers.
  • It does not trigger for certain keys like ALT, CTRL, SHIFT, and ESC in some browsers.
  • To detect key presses reliably, use the onkeydown event instead, as it works for all keys.

Syntax

In HTML

index.html
<element onkeypress="myScript">

In JS

script.js
object.onkeypress = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("keypress", myScript);

Example

::event-onkeypress ::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onkeypress Event</h2>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeypress="myFunction()">

<script>
function myFunction() {
  alert("You pressed a key inside the input field");
}
</script>

</body>
</html>

Values

Conclusion

The onkeypress event is a useful tool for capturing keyboard input in web applications. It allows developers to trigger specific actions when a key is pressed and released, enhancing interactivity by responding to user input efficiently.