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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay