Keylistener in Javascript

I am looking for a KeyListener for a game that I am developing in JavaScript. I have no idea how this will work in real code, but it will be something like this:

 if(keyPress == upKey) { playerSpriteX += 10; } else if(keyPress == downKey) { playerSpriteY -= 10; } 

etc...

I searched for it, and Google came up with AJAX-related things that I don’t understand yet. Is there a built-in function in JavaScript that does this?

+20
javascript key keyboard keylistener
source share
5 answers

Here is the update for modern browsers in 2019

 let playerSpriteX = 0; document.addEventListener('keyup', (e) => { if (e.code === "ArrowUp") playerSpriteX += 10 else if (e.code === "ArrowDown") playerSpriteX -= 10 document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX; }); 
 Click on this window to focus it, and hit keys up and down <br><br><br> <div id="test">playerSpriteX = 0</div> 

Original answer since 2013

 window.onkeyup = function(e) { var key = e.keyCode ? e.keyCode : e.which; if (key == 38) { playerSpriteX += 10; }else if (key == 40) { playerSpriteX -= 10; } } 

Fiddle

+45
source share

The code

 document.addEventListener('keydown', function(event){ alert(event.keyCode); } ); 

This returns the ascii key code. If you need a key representation, use event.key (this will return 'a', 'o', 'Alt' ...)

+13
source share

JSFIDDLE DEMO

If you do not want the event to be continuous (if you want the user to release a key each time), change onkeydown to onkeyup

 window.onkeydown = function (e) { var code = e.keyCode ? e.keyCode : e.which; if (code === 38) { //up key alert('up'); } else if (code === 40) { //down key alert('down'); } }; 
+8
source share

Have you checked out the small Mousetrap library?

Mousetrap is a simple JavaScript keyboard shortcut library.

+3
source share

A slightly more readable comparison is done by event.key in upper case (I used onkeyup - I need the event to fire once every time I press the key):

 window.onkeyup = function(event) { let key = event.key.toUpperCase(); if ( key == 'W' ) { // 'W' key is pressed } else if ( key == 'D' ) { // 'D' key is pressed } } 

Each key has its own code, output it by displaying the value of the variable "key" (for example, for the up arrow key it will be "ARROWUP" - (reduced to upper case))

+1
source share

All Articles