DEV Community

dwarfŧ
dwarfŧ

Posted on

key detection in javascript

intro
when I've been coding games in javascript i was always looking for a way to detect key presses without it being depreciated.

step 1
the first step is to create the detector.
you can do this by:

document.onkeydown = function (e) {
    console.log("key down");
};
Enter fullscreen mode Exit fullscreen mode

now if you press any key it will log "key down"

step 2
to detect a certain key (such as q) we need to listen for the e.key value. This will change every time a different key is pressed.
you can do this by typing:

document.onkeydown = function (e) {
    console.log(e.key);
};
Enter fullscreen mode Exit fullscreen mode

now, say if you pressed w, it would log w or if you press b it would log b.

step 3
if you want to do something when a certain key is pressed you can use if statements:

document.onkeydown = function (e) {
    if (e.key == "w") {
        console.log("up"); //logs up when w key pressed
    } else if (e.key == "s") {
        console.log("down"); //logs down when s key pressed
    }
};
Enter fullscreen mode Exit fullscreen mode

now when i press W it will log "up" (like many 2d games w is up) and when i press S it will log "down"

step 4
enjoy and code until your heart's content.

Top comments (0)