Detecting arrow key presses in JavaScript
Asked Answered
T

22

618

How do I detect when one of the arrow keys are pressed? I used this to find out:

function checkKey(e) {
    var event = window.event ? window.event : e;
    console.log(event.keyCode)
}

Though it worked for every other key, it didn't for arrow keys (maybe because the browser is supposed to scroll on these keys by default).

Tab answered 8/4, 2011 at 15:9 Comment(0)
A
939

Arrow keys are only triggered by onkeydown, not onkeypress.

The keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
Accelerant answered 8/4, 2011 at 15:13 Comment(12)
Some browsers do trigger keypress events for arrow keys, but you're right that keydown always works for arrow keys.Iridic
If you press %, you also get keyCode 37Azotic
@Azotic -- No, you get 53 with a keydown event. You get 37 with keypress, which is a different thingAccelerant
@1nfiniti onkeyup won't consider the repeated call of the keydown event when you hold the arrow down.Dire
:( arrow key presses not being visible on "keypress" puts serious limitations. You practically can't do things like "if (evt.which === 40) { itemIndex +=1; scrollToFunction(...);" on "keypress" - which should keep scrolling as long as you don't take your finger off the arrow key. If we are forced to do that on keydown or keyup, then it will only triger the event ONCE, and we'd have to keep stroking the keydown arrow to scroll to a newly marked element in a list, instead of just holding down the arrow key.Section
@Section - or also listen to onkeyup and stop the event there. Realistically you shouldn't be modifying UI behavior with Javascript, however.Accelerant
@MarkKahn yeah, it's just that you have to listen to 2 events to be able to accomplish functionality that should have been accessible through 1 event alone, in my opinion. It is possible though, yeah... Nothing's really impossible, there are always ways to do it. I just think it should have been accessible altogether through the keypress event alone. Unfortunately, it's not.Section
useful tool for confirming keycodes: blog.pothoven.net/2008/05/…Fante
keyup is most of the time what you wantEuripides
If you care about quick response then key up is "slow" for example if you made a game, you wouldn't want to act upon when the key is let go, you want to act as soon as the key registers, so you would want to do it on key down, but make sure not to repeat the key being held down until the key triggers it's associated key up and then you can reset it ready for another key down.Lemonade
Can you write a code example?Denise
Please do not use this solution anymore!! It is old and many browsers do not support it anymore!!! Instead, consider using the "event.key" instead.Consolation
T
297

On key up and down call function. There are different codes for each key.

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
    }
    else if (e.keyCode == '40') {
        // down arrow
    }
    else if (e.keyCode == '37') {
       // left arrow
    }
    else if (e.keyCode == '39') {
       // right arrow
    }

}
Tertullian answered 16/2, 2012 at 11:58 Comment(13)
What does the second line do?Prakrit
'e = e || window.event;'Prakrit
It will get the eventTertullian
To clarify, 'e || window.event' means that if 'e' is a defined value, it will be the result of the '||' expression. If 'e' is not defined, 'window.event' will be the result of the '||' expression. So it's basically shorthand for: e = e ? e : window.event; Or: if (typeof(e) === "undefined") { e = window.event; } Selfevident
It's to make it work on old versions of IE (pre IE9) where the event was not passed into the handler function.Suppressive
Just to note keyCode is a number and === should ideally be usedRankins
@alexrogins have you checked? jsfiddle.net/AjKjU/86 and jsfiddle.net/AjKjU/87.Tertullian
Sorry, I don't understand your what your fiddle is showing. Have I checked what? I have edited your answer, please can you approve it as it is correct? Should be jsfiddle.net/AjKjU/88Rankins
@Tertullian the point was that keyCode is a number and should be checked like keyCode === 32, not keyCode == '32' or keyCode === '32'.Shuler
keyCode is deprecated. Please see developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode Use key instead ie e.key === 'ArrowDown'Relator
Better than accepted answer because it actually gives code example.Denise
isnt e.keyCode deprecated and e.which as well ? is there any alternative to finding the ASCII code ?@TertullianMythos
As @SyedKhizaruddin pointed out, e.keyCode is deprecated. The answer should be updated.Planetstruck
T
290

event.key === "ArrowRight"...

More recent and much cleaner: use event.key. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!

node.addEventListener('keydown', function(event) {
    const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});

Verbose Handling:

switch (event.key) {
    case "ArrowLeft":
        // Left pressed
        break;
    case "ArrowRight":
        // Right pressed
        break;
    case "ArrowUp":
        // Up pressed
        break;
    case "ArrowDown":
        // Down pressed
        break;
}

Modern Switch Handling:

const callback = {
    "ArrowLeft"  : leftHandler,
    "ArrowRight" : rightHandler,
    "ArrowUp"    : upHandler,
    "ArrowDown"  : downHandler,
}[event.key]
callback?.()

NOTE: The old properties (.keyCode and .which) are Deprecated.

"w", "a", "s", "d" for direction, use event.code

To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code. This will preserve physical key location, even if resulting character changes.

event.key would be , on Dvorak and z on Azerty, making your game unplayable.

const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD

Optimally, you also allow key remapping, which benefits the player regardless of their situation.

P.S. event.code is the same for arrows

key Mozilla Docs

code Mozilla Docs

Supported Browsers

Toomin answered 27/5, 2017 at 4:43 Comment(5)
Thank you for using key and not keyCode, that was deprecated.Saturated
Note from MDN: Internet Explorer, Edge (16 and earlier), and Firefox (36 and earlier) use "Left", "Right", "Up", and "Down" instead of "ArrowLeft", "ArrowRight", "ArrowUp", and "ArrowDown".Erroneous
as event.keyCode is deprecated this should be the accepted answerForked
I just loved the modern switch handlingJaquenette
I presume that event.key === "ArrowRight" is not doing a string comparison to check a single keypress. Can anyone confirm?Hamper
E
102

Possibly the tersest formulation:

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 38:
            alert('up');
            break;
        case 39:
            alert('right');
            break;
        case 40:
            alert('down');
            break;
    }
};

Demo (thanks to user Angus Grant): http://jsfiddle.net/angusgrant/E3tE6/

This should work cross-browser. Leave a comment if there is a browser where it does not work.

There are other ways to get the key code (e.which, e.charCode, and window.event instead of e), but they should not be necessary. You can try most of them out at http://www.asquare.net/javascript/tests/KeyCode.html. Note that event.keycode does not work with onkeypress in Firefox, but it does work with onkeydown.

Evaginate answered 29/7, 2013 at 16:16 Comment(1)
I had to look up the definition of terse, then I (sprightfully) postulated that tersest was an improper conjugation; alas, I concede: my solicitude was refutable.Barolet
I
22

Use keydown, not keypress for non-printable keys such as arrow keys:

function checkKey(e) {
    e = e || window.event;
    alert(e.keyCode);
}

document.onkeydown = checkKey;

The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html

Iridic answered 8/4, 2011 at 15:39 Comment(1)
Now keypress has been marked as deprecatedSimasimah
P
20

Modern answer since keyCode is now deprecated in favor of key:

document.onkeydown = function (e) {
    switch (e.key) {
        case 'ArrowUp':
            // up arrow
            break;
        case 'ArrowDown':
            // down arrow
            break;
        case 'ArrowLeft':
            // left arrow
            break;
        case 'ArrowRight':
            // right arrow
    }
};
Preterit answered 5/8, 2017 at 20:23 Comment(0)
F
18

I believe the most recent method would be:

document.addEventListener("keydown", function(event) {
  event.preventDefault();
  const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
  switch (key) { // change to event.key to key to use the above variable
    case "ArrowLeft":
      // Left pressed
      <do something>
      break;
    case "ArrowRight":
      // Right pressed
      <do something>
      break;
    case "ArrowUp":
      // Up pressed
      <do something>
      break;
    case "ArrowDown":
      // Down pressed
      <do something>
      break;
  }
});

This assumes the developer wants the code to be active anywhere on the page and the client should ignore any other key presses. Eliminate the event.preventDefault(); line if keypresses, including those caught by this handler should still be active.

Frilling answered 9/7, 2019 at 17:22 Comment(0)
F
9
function checkArrowKeys(e){
    var arrs= ['left', 'up', 'right', 'down'], 
    key= window.event? event.keyCode: e.keyCode;
    if(key && key>36 && key<41) alert(arrs[key-37]);
}
document.onkeydown= checkArrowKeys;
Ferula answered 8/4, 2011 at 15:42 Comment(1)
Doesn't it worth to put arrs outside of the function? No need to recreate it every callAluminiferous
O
9

Here's an example implementation:

var targetElement = $0 || document.body;

function getArrowKeyDirection (keyCode) {
  return {
    37: 'left',
    39: 'right',
    38: 'up',
    40: 'down'
  }[keyCode];
}

function isArrowKey (keyCode) {
  return !!getArrowKeyDirection(keyCode);
}

targetElement.addEventListener('keydown', function (event) {
  var direction,
      keyCode = event.keyCode;

  if (isArrowKey(keyCode)) {
    direction = getArrowKeyDirection(keyCode);

    console.log(direction);
  }
});
Occurrence answered 17/1, 2015 at 23:42 Comment(1)
I am getting $0 is not defined var targetElement = typeof $0 !== 'undefined' ? $0 : document.body; or just: var targetElement = document.body; is okCain
H
8

Here's how I did it:

var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
    keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
    delete keystate[e.keyCode];
});

if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
Heliotherapy answered 31/7, 2015 at 16:48 Comment(0)
G
6

Arrow Keys are triggered on keyup

$(document).on("keyup", "body", function(e) {
 if (e.keyCode == 38) {
    // up arrow
    console.log("up arrow")
  }
  if (e.keyCode == 40) {
      // down arrow
      console.log("down arrow")
  }
  if (e.keyCode == 37) {
    // left arrow
    console.log("lefy arrow")
  }
  if (e.keyCode == 39) {
    // right arrow
    console.log("right arrow")
  }
})

onkeydown allows ctrl, alt, shits

onkeyup allows tab, up arrows, down arrows, left arrows, down arrows

Gauntlet answered 13/1, 2020 at 6:24 Comment(0)
W
4

I've been able to trap them with jQuery:

$(document).keypress(function (eventObject) {
    alert(eventObject.keyCode);
});

An example: http://jsfiddle.net/AjKjU/

Whisenhunt answered 8/4, 2011 at 15:14 Comment(1)
keypress won't work with arrow keys. You have to use $(document).on('keydown', function() {...}) insteadScudder
I
4

That is the working code for chrome and firefox

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script type="text/javascript">

    function leftArrowPressed() {
      alert("leftArrowPressed" );
      window.location = prevUrl  
    }

    function rightArrowPressed() {
      alert("rightArrowPressed" );
      window.location = nextUrl  
    }
    function topArrowPressed() {
      alert("topArrowPressed" );
      window.location = prevUrl  
    }

    function downArrowPressed() {
      alert("downArrowPressed" );
      window.location = nextUrl  
    }

        document.onkeydown = function(evt) {
                        var nextPage = $("#next_page_link")
                        var prevPage = $("#previous_page_link")
                        nextUrl = nextPage.attr("href")
                        prevUrl = prevPage.attr("href")
        evt = evt || window.event;
        switch (evt.keyCode) {
                case 37:
                leftArrowPressed(nextUrl);
                break;

                case 38:
                topArrowPressed(nextUrl);
                break;

                 case 39:
                rightArrowPressed(prevUrl);
                break;

                case 40:
                downArrowPressed(prevUrl);
                break;

        }
    };


</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a> 
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
 </p>
</body>
</html>
Insolvable answered 10/12, 2013 at 20:31 Comment(0)
S
3

I was also looking for this answer until I came across this post.

I've found another solution to know the keycode of the different keys, courtesy to my problem. I just wanted to share my solution.

Just use keyup/keydown event to write the value in the console/alert the same using event.keyCode. like-

console.log(event.keyCode) 

// or

alert(event.keyCode)

- rupam

Socrates answered 30/1, 2013 at 5:43 Comment(0)
C
3

That's shorter.

function IsArrows (e) { return (e.keyCode >= 37 && e.keyCode <= 40); }

Cornhusk answered 18/11, 2014 at 7:39 Comment(1)
short is good: if ([37,38,39,40].indexOf(e.keyCode)!=-1){ console.log('arrow pressed') }Ellinger
G
3

This library rocks! https://craig.is/killing/mice

Mousetrap.bind('up up down down left right left right b a enter', function() {
    highlight([21, 22, 23]);
});

You need to press the sequence a bit fast to highlight the code in that page though.

Gertrudegertrudis answered 27/5, 2017 at 6:2 Comment(0)
A
3

With key and ES6.

This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock is on.

const element = document.querySelector("textarea"),
  ArrowRight = k => {
    console.log(k);
  },
  ArrowLeft = k => {
    console.log(k);
  },
  ArrowUp = k => {
    console.log(k);
  },
  ArrowDown = k => {
    console.log(k);
  },
  handler = {
    ArrowRight,
    ArrowLeft,
    ArrowUp,
    ArrowDown
  };

element.addEventListener("keydown", e => {
  const k = e.key;

  if (handler.hasOwnProperty(k)) {
    handler[k](k);
  }
});
<p>Click the textarea then try the arrows</p>
<textarea></textarea>
Angularity answered 5/2, 2020 at 9:25 Comment(0)
A
2

Re answers that you need keydown not keypress.

Assuming you want to move something continuously while the key is pressed, I find that keydown works for all browsers except Opera. For Opera, keydown only triggers on 1st press. To accommodate Opera use:

document.onkeydown = checkKey;
document.onkeypress = checkKey;
function checkKey(e)
{ etc etc
Astronomy answered 18/2, 2013 at 11:3 Comment(0)
U
2

In the off chance you're still developing with desktops in mind in 2023:

KeyboardEvent: keyCode property has been deprecated

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Use the ket property https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

// run snippet and click a key to see which key you clicked:

document.addEventListener('keydown', (event) => { 
 alert(`You clicked ${event.key}`);
});
Ultimogeniture answered 30/6, 2023 at 11:32 Comment(0)
R
1

If you use jquery then you can also do like this,

 $(document).on("keydown", '.class_name', function (event) {
    if (event.keyCode == 37) {
        console.log('left arrow pressed');
    }
    if (event.keyCode == 38) {
        console.log('up arrow pressed');
    }
    if (event.keyCode == 39) {
        console.log('right arrow pressed');
    }
    if (event.keyCode == 40) {
        console.log('down arrow pressed');
    }
 });
Roquefort answered 29/10, 2019 at 9:27 Comment(0)
C
0

control the Key codes %=37 and &=38... and only arrow keys left=37 up=38

function IsArrows (e) {
   return ( !evt.shiftKey && (e.keyCode >= 37 && e.keyCode <= 40)); 
}
Catchpole answered 26/10, 2016 at 6:48 Comment(0)
V
0

If you want to detect arrow keypresses but not need specific in Javascript

function checkKey(e) {
   if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
    // do something
   };
}
Venuti answered 20/1, 2019 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.