How To Detect A Key Press

Table of contents:

How To Detect A Key Press
How To Detect A Key Press

Video: How To Detect A Key Press

Video: How To Detect A Key Press
Video: How To Detect Key Presses In JavaScript 2024, December
Anonim

JavaScript is an object-oriented scripting language. It is most often used to programmatically define the reactions of pages to user actions. The presence of java-scripts on the page slightly burdens their volume, so it is not recommended to use complex programmatic constructs.

How to detect a key press
How to detect a key press

Necessary

administrator rights

Instructions

Step 1

To recognize when a keyboard button is pressed, the onkeydown event, which is part of the page, is used in the body tag. The logic for writing code for this event is quite simple: and the value in quotes can be either a standalone code or a function call. To set the response to a key press in the form of a text message, write the following code: body. In this case, the alert () /

Step 2

To determine which button was pressed, you need to type the following code: body. This code snippet refers to the event object, or rather, to its keyCode property, which returns the numeric code of the pressed button. If on the site you need to determine which key was pressed, integrate this code on the page on which all this should be done.

Step 3

To recognize the keyboard shortcut, you need to complicate the code a little by adding the condition: body. That is, if the codes of the pressed buttons correspond to “71”, the text message “Ctrl + G” should be output. Naturally, instead of the alert function, you can write your own reaction. As a rule, every web designer tries to adjust the site configuration to suit his needs, so the display methods can be completely different.

Step 4

There is also an onkeypress handler in javascript, which has a similar purpose. The main difference of this handler is that in order for this event to occur (and the subsequent response of the handler), the button must not only be pressed, but also then released.

Recommended: