Onkeypress Event in JavaScript

In JavaScript, the onkeypress event serves as an attribute for event handling that designates a function to execute when a key is pressed and subsequently released on the keyboard. This particular event is activated when a key is physically depressed and then let go.

The onkeypress event refers to a keyboard interaction that initiates a sequence of actions while a key remains pressed down. You can link it to a JavaScript function to define the intended response or behavior. This event is commonly utilized to detect character input, offering details regarding the character code or Unicode representation of the key. The event object contains further details about the pressed key, including properties like keyCode or charCode. This event occurs every time a key is activated.

Onkeypress Event Syntax

The onkeypress event can be incorporated into the script through several approaches. In this section, we will outline the syntax for each approach along with a detailed explanation.

1. For JavaScript Function

Syntax:

Example

function functionName(event) { ... }

The JavaScript function mentioned earlier takes an event object as its parameter, which holds details regarding the key press action.

2. For HTML

Syntax:

Example

<element onkeypress="functionName(event)">

This designates a JavaScript function that will run whenever a key is pressed on the designated element (such as a <input> field).

3. For EventListener

Syntax:

Example

const element = document.getElementById("myInput");
element.addEventListener("keypress", handleKeyPress);

This method is increasingly favored in contemporary web development due to its flexibility. It enables the dynamic addition and removal of event listeners.

Implementation of the Onkeypress Event

In this part of the article, we will explore the hands-on application of the onkeypress event for various situations.

1. For JavaScript

A widely utilized approach involves employing the onkeypress event alongside JavaScript functions. In the following example, we will illustrate a comprehensive execution of the onkeypress event through the use of JavaScript functions.

Code:

Example

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

2. For HTML

In order to utilize the onkeypress event in HTML, it is necessary to include the onkeypress attribute within a specific HTML element. The value assigned to this attribute should correspond to a JavaScript function that is defined in the JavaScript section of your code. Presented below is a practical example illustrating the implementation of an onkeypress event in HTML.

Code:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>onkeypress EventListener Demo</title>
</head>
<html>
<body>

<p><b>The function will trigger when the user presses a key in the input text field.</b></p>

<input type="text" onkeypress="myFunction()">

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

</body>
</html>

Output:

3. For EventListener

Code:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>onkeypress EventListener Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 50px;
        }

        input {
            font-size: 16px;
            padding: 10px;
        }

        p {
            font-size: 18px;
            margin-top: 20px;
            color: #333;
        }
    </style>
</head>
<body>

<input type="text" id="textInput">

<p id="keyInfo">Press a key to see information.</p>

<script>
    // Get the input field
    const inputField = document.getElementById('textInput');

    // Add an event listener for the keypress event
    inputField.addEventListener('keypress', logKeyPress);

    function logKeyPress(event) {
        // Get the pressed key's character
        const pressedKey = String.fromCharCode(event.charCode);

        // Get the keyCode of the pressed key
        const keyCode = event.keyCode;

        // Display information about the pressed key
        document.getElementById('keyInfo').innerHTML = `Pressed Key: ${pressedKey} | KeyCode: ${keyCode}`;
    }
</script>

</body>
</html>

Output:

Browser Support

Browser Name Supported on versions
Internet Explorer version >= 7(Aug 2001)
Mozilla Firefox version >= 2(Oct 2006)
Microsoft Edge version >= 12(Jul 2015)
Google Chrome version >= 4(Jan 2010)
Safari version >= 3.1(Mar 2008)
Opera version >= 9.5

For tracking keyboard key presses in JavaScript, especially in form fields or interactive apps, an onkeypress event is an essential tool. It provides information about the character code or Unicode value of a key, causing actions to be triggered when the key is pushed and released. There are three ways to create an event: event listeners, independent JavaScript methods, and inline HTML attributes.

Each serves a distinct purpose and has its own syntax. Through the utilization of JavaScript functions, HTML attributes, and event listeners, practical illustrations demonstrated scenarios in which alerts are triggered and details regarding the key that was pressed are displayed. Developing dynamic, responsive websites that accommodate user keyboard input necessitates a grasp of and expertise in the onkeypress event.

Input Required

This code uses input(). Please provide values below: