Home > Web Front-end > JS Tutorial > How Can I Capture Arrow Keystrokes in JavaScript and jQuery?

How Can I Capture Arrow Keystrokes in JavaScript and jQuery?

Patricia Arquette
Release: 2024-10-29 08:50:02
Original
1124 people have browsed it

How Can I Capture Arrow Keystrokes in JavaScript and jQuery?

Capturing Arrow Keystrokes with JS and jQuery

Binding functions to arrow keys in Javascript and jQuery is a common requirement for keyboard navigation. While the js-hotkey plugin for jQuery extends the built-in bind function, it lacks support for arrow keys.

To address this, here's a straightforward solution:

<code class="javascript">document.onkeydown = function(e) {
    switch(e.which) {
        case 37: // left
        break;

        case 38: // up
        break;

        case 39: // right
        break;

        case 40: // down
        break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
};</code>
Copy after login

This code captures keystrokes for the left, up, right, and down arrow keys using the switch statement. You can define the desired actions within each case.

Note that for browsers that don't support the which property (such as IE8), modify the function body as follows:

<code class="javascript">document.onkeydown = function(e) {
    e = e || window.event;
    switch(e.which || e.keyCode) {
        case 37: // left
        break;

        // ...
    }
};</code>
Copy after login

Alternatively, for modern browsers, the KeyboardEvent.key property can be used to detect arrow keys, as shown in this example:

<code class="javascript">document.onkeydown = function(e) {
    switch(e.key) {
        case "ArrowLeft": // left
        break;

        // ...
    }
};</code>
Copy after login

By implementing this code, you can effortlessly bind functions to arrow keys in your JavaScript or jQuery applications.

The above is the detailed content of How Can I Capture Arrow Keystrokes in JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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