Move Elements On Web Page Using Java-Script

Move Elements On Web Page

In this tutorial, you will learn how to move elements on the screen by pressing arrow keys. To accomplish this concept, You can make use of JavaScript, HTML, and CSS.

The idea behind this is when a user press direction keys which are up down left and right then some element move on the page according to the key press.

The logic is very simple and by enhancing that login you can create a simple game on the web using JavaScript today it’s just a demo how to move elements across the web page.

move airplane image on screen
Move Elements i.e. aeroplane image on the screen

I use simple conditions if and use HTML event keypress because I want to move my element on keypress.

Check for the Key Pressed

First, I check if the key is pressed or not and when a key is pressed then call a function.

First, get the element which I want to move.

Then take two variables, initialize them with element’s default top and left positions.

Then save the value of key press in variable e using window.event.

Now I know the ASCII of all four directional key.


So first I check what the value of keycode property and then according to it increase or decrease the values from left, right, top or bottom.

JavaScript Rotate

Now to rotate the element in the direction of key CSS transform property is used and rotates it in some degree.


Complete JavaScript Code


Image to Move on the Screen

And in HTML code, we have only one div, and this is also empty.

Apply CSS Properties

In CSS, we set the background-image of that div and set some width and height of the div.

If user exceeded screen from the top or left, then it will stop him and show a pop-up warning.

show dialog box on screen limit exceed
Show dialogue box on screen limit exceed

Download Amazing Aeroplane Moving on Screen


Watch Live Demo Of Amazing Aeroplane Moving on Screen

Leave a Reply

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