Ask coding questions

← Back to all posts
How to detect keypress in javascript
[deleted]

does anyone know how to detect a keypress in javascript? thanks!

Answered by ruiwenge2 (544) [earned 5 cycles]
View Answer
Comments
hotnewtop
ruiwenge2 (544)

@MadPickle There are a few ways to do this. One way is that when you create an html element, you can add an "onkeypress" attribute.

For example, if you want to detect keypress in a div element, you can type this:

<div onkeypress="myFunction()"></div>

and myFunction() is a function in the javascript code.

You can also do
document.addEventListener("keydown", myFunction);

[deleted]

@ruiwenge2 how do you find out what key the user pressed?

ruiwenge2 (544)

@MadPickle

document.addEventListener("keydown", function(event){
     if(event.key == "KEYNAME"){
      // do something here
     }
   });
[deleted]

code: // Variables
var x = 0;
var y = 0;

function setup() {
createCanvas(750, 400);
}

function draw() {
let c = color('blue');
fill(c);
background(255);
textSize(30);
text('Sonic : the lost emerald', 200, 200);
rect(x, y, 50, 50);
if (this.keyPressed(87)) {
this.y -= 5;
} else if (keyIsDown(83)) {
this.y += 5;
} else if (keyIsDown(65)) {
this.x -= 5;
} else if (keyIsDown(68)) {
this.x += 5
}
}

dolphin30 (0)

Suggestion: Add the code to it