Latest web development tutorials
 

onkeypress Event

< Event Object

Example

Execute a JavaScript when a user presses a key:

<input type="text" onkeypress="myFunction()">
Try it Yourself »

Definition and Usage

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

Tip: The order of events related to the onkeypress event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.


Browser Support

Event
onkeypress Yes Yes Yes Yes Yes

Syntax

In HTML:

<element onkeypress="myScript">
Try it Yourself »

In JavaScript:

object.onkeypress=function(){myScript};
Try it Yourself »

In JavaScript, using the addEventListener() method:

object.addEventListener("keypress", myScript);
Try it Yourself »

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.


Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: 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

< Event Object