Detect arrow key press in JavaScript

By Faruque Ahamed Mollick

In this post, we are going to see how to detect if arrow key pressed from the keyboard using JavaScript with example code snippets. Before we go forward we should get some information.

Every key on the keyboard has a unique key code. Here we are going to detect if arrow key pressed. Well, on our keyboard there are four arrow keys. We can see left, right, up and download keys on our keyboard. These keys also have their unique key code that can be used by JavaScript to detect if these keys pressed or not.

Copy text to clipboard on click using JavaScript

Disable right click, copy, cut on web page using jQuery

Left arrow key has the key code 37, up arrow key has code 38, the right key has the code 39 and the down arrow key has the key code 40. We are going to use these key codes in our JavaScript code.

Here we will use onkeydown JavaScript event so that when the user presses one of the arrow keys, it will be detected by our javaScript.

Below is the complete JavaScript code:

<script type="text/javascript">
    document.onkeydown = function(event) {
        switch (event.keyCode) {
           case 37:
                alert('Left key pressed');
           case 38:
                alert('Up key pressed');
           case 39:
                alert('Right key pressed');
           case 40:
                alert('Down key pressed');

After you place the above JavaScript code you can test your HTML file on your browser. This code is supported by most of the modern web browser including Chrome, Firefox Safari etc. As you can see, the code we have is just of few lines and simple enough but do a lot of performance.

Make a div element draggable using jQuery UI

If you test the code on your browser, you will see the alert box whenever you press one of the arrow keys. In our code, we have used switch case statement instead of if statement. If you want, then you can also use if statement. But I think switch case statement is more readable and easy way then if statement.

With the same process, you can detect any key press on the keyboard. You just need the key code of that key. By the way, here in this post, We have seen how to detect arrow key press in javaScript. I hope you like this post and it will be helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *