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

How to Detect Arrow Key Presses in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 10:54:03533browse

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);
    }
}

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;
        }
    }
}

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:
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