Move an Element with Arrow Keys in JavaScript

I am again with a JavaScript tutorial that can make newbies feel great. In this tutorial, I am going to show you how to consistently move an element with arrow keys.

I already show you how to detect arrow key pressed. Now, this tutorial is going to be one step advance because here I am going to show you how to detect arrow key pressed as well as move our element with arrow keys.

First of all, we have to create our element which we want to move with arrow keys. below is our HTML element:

<div id="myId"></div>

After that, below is our CSS to give our element a looks like a red ball:

#myId {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background-color: red;
  transition: 0.2s;
}

Next, we are going to use JavaScript to move our element with arrow keys.

Below is our JavaScript code that can move our element with the arrow key pressed:

document.onkeydown = detectKey;

function detectKey(e) {

    var posLeft = document.getElementById('myId').offsetLeft;
    var posTop = document.getElementById('myId').offsetTop;

    e = e || window.event;

    if (e.keyCode == '38') {
        // up arrow
        document.getElementById('myId').style.marginTop  = (posTop-58)+"px";
    }
    else if (e.keyCode == '40') {
        // down arrow
        document.getElementById('myId').style.marginTop  = (posTop+58)+"px";
    }
    else if (e.keyCode == '37') {
       // left arrow
        document.getElementById('myId').style.marginLeft  = (posLeft-58)+"px";
    }
    else if (e.keyCode == '39') {
       // right arrow
        document.getElementById('myId').style.marginLeft  = (posLeft+58)+"px";
    }

}

First of all, we get and store the position of the element in the above code. We are using offsetLeft and offsetRight property to get the element position.

We have used the key code to detect arrow key pressed.

Each and every key on the computer keyboard has a unique code. With this key code, we can detect which key the user press from the keyboard.

The arrow key up has key code 38. Similarly, down arrow has the 40, the left arrow has 37 and right arrow has 39 key code.

In our JavaScript code, we are checking the keycode and if it is matched with any one of the arrow keys, it will move our element by 58 pixels.

 

Also, read:

 

Now we can run our code on our browser. If we test it on our browser, we can see that the red ball moving with the arrow key pressed.

So we have successfully able to move an element with arrow key pressed in JavaScript.

One response to “Move an Element with Arrow Keys in JavaScript”

  1. Angela Jackson says:

    I have a crossword puzzle code and I am trying to move the focus of cursor when the user presses a keyboard arrow. Can you help with this code. Can I send you the code. It is in html, java and css.
    Thanks
    Angela E. Jackson
    Jackson108@aol.com

Leave a Reply

Your email address will not be published. Required fields are marked *