onkeypress Event

Definition and usage

The onkeypress event occurs when the user presses a key (on the keyboard).

Tip:Event order related to onkeypress event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

Note:Not all keys (such as ALT, CTRL, SHIFT, ESC) will trigger the onkeypress event in all browsers. If you want to detect whether the user has pressed a specific key, please use the onkeydown event instead, as it applies to all keys.

Example

Execute JavaScript when the user presses a key:

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

Try it yourself

Syntax

In HTML:

<element onkeypress="myScript">

Try it yourself

In JavaScript:

object.onkeypress = function(){myScript};

Try it yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("keypress", myScript);

Try it yourself

Note:Internet Explorer 8 or earlier versions do not support addEventListener() method.

Technical details

Bubbling: Support
Cancelable: Support
Event types: KeyboardEvent
Supported HTML tags: All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title>
DOM Version: Level 2 Events

Browser Support

Events Chrome IE Firefox Safari Opera
onkeypress Support Support Support Support Support