Home > Web Front-end > JS Tutorial > body text

How to Handle Arrow Key Input in JavaScript Using Key Events?

Linda Hamilton
Release: 2024-11-03 00:07:03
Original
582 people have browsed it

How to Handle Arrow Key Input in JavaScript Using Key Events?

Handling Arrow Key Input in Javascript Using Key Events

Detecting and handling input from arrow keys can be useful for various scenarios in web development. This can be achieved through the built-in key event handling capabilities of the browser.

Solution Using Javascript Key Events:

The provided Javascript code utilizes the document.onkeydown event handler to listen for key presses. When a key is pressed, the event.which property is used to determine the key code. Arrow key codes correspond to the following values:

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

The switch statement handles these key codes and allows you to define your custom logic for each key press.

Detailed Implementation:

<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

Additional Considerations:

  • For Internet Explorer 8 support, modify the beginning of the function as follows: e = e || window.event; switch(e.which || e.keyCode) {}
  • As of 2020, KeyboardEvent.which is deprecated. For a more modern solution, use KeyboardEvent.key:
<code class="javascript">document.onkeydown = function(e) {
    switch(e.key) {
        case "ArrowLeft": // left
        break;

        case "ArrowUp": // up
        break;

        case "ArrowRight": // right
        break;

        case "ArrowDown": // down
        break;

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

The above is the detailed content of How to Handle Arrow Key Input in JavaScript Using Key Events?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!