Learn to Code via Tutorials on Repl.it!

← Back to all posts
JavaScript KeyInput! (KeyDown)
PixiGem (153)

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 :)

Comments
hotnewtop