JS onkeypress event

The onkeypress event in JavaScript is triggered when a key is pressed on the keyboard. This event is fired for printable keys, meaning it excludes keys like Shift, Ctrl, Alt, and Esc. It can be used to perform specific actions while a user is typing in an input field or interacting with the keyboard in other ways.

Usage of onkeypress Attribute in HTML

The onkeypress attribute can be added directly to HTML elements such as <input>, <textarea>, or any element that can receive keyboard input. When the specified key is pressed, the function associated with the onkeypress event is executed.

Example:

<element onkeypress="functionName(event)"></element>

Example:

<label for="textInput">Type something:</label><br> <input type="text" id="textInput" onkeypress="displayKey(event)"><br> <p id="output"></p><br> <script><br>     function displayKey(event) {<br>         var char = String.fromCharCode(event.keyCode);<br>         document.getElementById('output').innerText = "You pressed: " + char;<br>     }<br> </script>

Output:

Important Notes

1. Event Object: The onkeypress event handler function takes an event object as an argument, which provides information about the key that was pressed. The keyCode or which property of the event object can be used to determine the specific key pressed.

2. Deprecated: The onkeypress event has been deprecated in modern web development. Instead, it is recommended to use onkeydown or onkeyup events for better compatibility and more comprehensive handling of keyboard events.

Modern Alternatives: onkeydown and onkeyup

While onkeypress is still widely supported, it's considered better practice to use onkeydown or onkeyup events for handling keyboard input.

onkeydown: Fires when a key is pressed down. Suitable for detecting keys like Shift, Ctrl, Alt, and function keys.

onkeyup: Fires when a key is released.