DEV Community

Cover image for How To Move Objects Around Your Webpage Using Arrow Keys In JavaScript
Jennifer Eze
Jennifer Eze

Posted on

How To Move Objects Around Your Webpage Using Arrow Keys In JavaScript

 a man using the keyboard

Introduction

One of the difficulties that new developers face is not knowing how to move an image across the screen smoothly and at an angle. I could move it 45 degrees by moving one pixel up/down the x-axis and one pixel up/down the y-axis, but that's not precise enough. How would I go about moving it at an exact angle? Isn't there supposed to be a function that rounds it to the nearest pixel?

What are arrow keys?

The arrow keys, also known as cursor keys, direction keys, and navigation keys, are typically found on a computer keyboard between the standard section and the numeric pad. The arrow keys are located between the keyboard and the keypad. It consists of four keys: left arrow (back arrow), up arrow, down arrow, and right arrow (forward arrow). The image depicts how the arrow keys may appear on your keyboard.

The Arrow Keys

How To Move An Object With Arrow Keys In JavaScript.

I am saying objects I mean HTML elements. Here we will use a div element and try to move it around using arrow keys. So let's start if you're ready.

In your HTML structure <!DOCTYPE html>
Link your stylesheet
Link your script.js in the body
put a div element with a class of circle

You will get an input like this;

HTML Code
After that go to your style sheet and give it some height and width etc.
CSS Code
Here is your output.
The Interface of the Code
Move to your script file and start working on it.

JavaScript Code
Now, that is going to be the output of your script file. when you view this on your browser. gently tap the arrow keys and see how the objects move up when you tap the up arrow key. The object will move downwards when the down arrow key is pressed. and so on just like that. EASY i guess.

Conclusion

Finally, we have come to the completion of this tutorial and hopefully, you got value from it.
Thanks for reading, please hit the like, clap, or heart button to show some love, I will see you in the next tutorial…

We have learnt what arrow keys are and how to move objects around your page using arrow keys in JavaScript.

If you have any questions, please leave it in the comments. Like and share, and till next time, all the best!

About the Author

I am Jenifer Eze, an enthusiastic developer with a passion for JavaScript, Bootstrap, PHP, HTML & CSS.
I work as a freelancer, building websites for clients, and love writing technical tutorials to teach others what I do. I am eager to hear from you. Reach me on LinkedIn, GitHub, or my website.

Top comments (0)