Home > Web Front-end > JS Tutorial > How to Detect Arrow Key Presses in JavaScript?

How to Detect Arrow Key Presses in JavaScript?

Linda Hamilton
Release: 2024-11-10 10:54:03
Original
538 people have browsed it

How to Detect Arrow Key Presses in JavaScript?

Detecting Arrow Key Presses in JavaScript

Determining when arrow keys are pressed in JavaScript can be challenging because browsers interpret them differently due to default scrolling behavior.

Using onkeydown Event Listener

As mentioned in the issue, the onkeypress event does not capture arrow key presses. Instead, you need to use the onkeydown event listener. Modify your function as follows:

function checkKey(e) {
    var event = window.event ? window.event : e;
    if (event.type === "keydown") {
        console.log(event.keyCode);
    }
}
Copy after login

Keycodes for Arrow Keys

The keycodes associated with the arrow keys are:

  • Left: 37
  • Up: 38
  • Right: 39
  • Down: 40

By using these keycodes within your condition, you can specifically detect arrow key presses:

function checkKey(e) {
    var event = window.event ? window.event : e;
    if (event.type === "keydown") {
        switch (event.keyCode) {
            case 37:
                // Left key pressed
                break;
            case 38:
                // Up key pressed
                break;
            case 39:
                // Right key pressed
                break;
            case 40:
                // Down key pressed
                break;
        }
    }
}
Copy after login

The above is the detailed content of How to Detect Arrow Key Presses in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template