Key Press Events

When an event is triggered information about the event is stored in a global variable named event which is passed to the event handler.  When a keyboard key is pressed, a keydown event is triggered and a unique value for the key that was pressed is stored in the keyCode property of the event object.

The JavaScript below registers an event handler for the keydown event and prints to the console the value of keyCode.

var keyDown = function(event) { 

window.addEventListener('keydown', keyDown);

Moving an Element in the Direction of the Arrow Keys

Suppose we have a div defined in an HTML file with its id attribute set to “box”.

    <div id="box">

Suppose also that we have stylized the box with the following CSS rule.

 #box {
     width: 20px;
     height: 20px;
     background-color: red;
     position: relative;

Since the div has its position set to relative, we can position the div anywhere on the page using the top and left properties.

Below is JavaScript code that moves the box around the screen when the user presses the arrow keys on the keyboard.

var x = 0;
var y = 0;

var keyDown = function(event) { 
    var key = event.keyCode; 

    if (key == 37) { x -= 10; } 
    else if (key == 38) { y -= 10;} 
    else if (key == 39) { x += 10;} 
    else if (key == 40) { y += 10;} 

    var box = document.getElementById("box"); = x + "px"; = y + "px"; 
window.addEventListener('keydown', keyDown);

© 2018 – 2020, Eric. All rights reserved.