Skip to content
← Back to Community
JavaScript KeyInput! (KeyDown)
Profile icon
PixiGem

This tutorial, you'll learn how to use the JavaScript KeyInput, so let's get started!

for example, we'll create a simple webpage that has a red canvas, whenever we click 'B' on our keyboard, it changes to blue, and 'R' for red. (go to the below repl)

HTML

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JavaScript keyInput (keydown)</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <canvas style="width: 250px;height:250px;background: red"> <script src="script.js"></script> </body> </html>

Cool! we just created our red canvas!

JavaScript -

first, we need to add an event listener to our webpage -

document.addEventListener("keydown", function(event){ /*this function runs when we click something on our keyboard(keydown event)*/ //if statement(code) })

now, check for the key we press, every key on the keyboard has a code in javascript, here is the list of them -

http://gcctech.org/csc/javascript/javascript_keycodes.htm

that was very loooooong, now coming to the if statement, here is the code -

document.addEventListener("keydown", function(event) { if (event.keyCode == 66 /*keycode for B*/) { document.getElementById('box').style.background = "blue" // make the canvas blue } });

Upvote if you find this tutorial helpful :)

Voters
Profile icon
abirdThePro
Profile icon
imnew12
Profile icon
Alexify
Profile icon
LegendaryWolf
Profile icon
PixiGem
Comments
hotnewtop
Profile icon
QuickV

Nice :D

Profile icon
GwendolineBinya

I pressed B and R nothing happens, Letters B & R just appear on the console...........

Profile icon
PixiGem

@GwendolineBinya which browser do you use chap?
BTW open it in a new tab?
or probably this code is outdated
WELL TRY IT AGAIN!!!!!
or maybe copy paste this code in ur own repl and try it

Profile icon
GwendolineBinya

@PixiGem am using chrome and my operating system is Ubuntu.Can you please help am actually failing to fire keyboard events in JavaScript

Profile icon
PixiGem

@GwendolineBinya maybe try copy pasting the code in ur PC's code editor...

Profile icon
GwendolineBinya

@PixiGem I tried that it didn't work

Profile icon
PixiGem

@GwendolineBinya I think u forgot the .css and .js files, maybe?

Profile icon
GwendolineBinya

@PixiGem now sorted had to put the defer attribute to script tag,am using chrome

Profile icon
NextLevel3

you have deserve more upvote for great information , I have learned JavaScript KeyInput. i also share very informative a Toonly Lifetime