Move an Element to Mouse Position in JavaScript

Are you ready to play with JavaScript? In this tutorial, I am going to show you how you can move an element to mouse position in JavaScript.

Isn’t not going to be interesting?

I hope you are excited to see how I am going to move an element with the movement of the mouse cursor.

Let’s see.

First of all, let’s create our HTML element which we are going to move to the mouse position.

Below is our HTML element:

<div id=”myId”></div>

Now we below are few lines of CSS code to give it a looks like a small red ball:

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

If you run it on your browser, you will able to see a small red ball. But nothing will happen now. After we add our JavaScript code, you can see the small red ball on the screen moving with the movement of the mouse. Here we are actually going to move an element with mouse movement.

You can notice in our CSS code, that we have added a CSS transition property. This is to make it more attractive.

Now below is our JavaScript code which is the main part of our tutorial:

document.onmousemove = function(e) { 
    var x = e.clientX; 
    var y = e.clientY; 
    document.getElementById('myId').style.marginLeft  = x+"px";
    document.getElementById('myId').style.marginTop  = y+"px";

In the above JavaScript code, we have used the clientX to get the position of our element from left and clientY to get the position of our element from the top.

The clientX and ClientY property return the horizontal and vertical position of the mouse pointer when the mouse event triggered.

After that, we set the DOM CSS marginLeft and marginTop property to our element.

Basically, in this tutorial, we have taken the x and y coordinate position of the mouse cursor and then apply it as the margin to our red ball or our element.

To detect the mouse move, we have used onmousemove Event so that whenever we move our mouse, we get the position of the pointer. Depending on the mouse position, we set the CSS margin to the red ball.

Now the code is ready to test and you can run it on your browser. You can see that if you move your mouse on the page, then the red ball also move to the mouse position. With the movement of your mouse pointer, the red ball also moves in a nice way.


Also, read:


So we have successfully able to move an element to mouse position in JavaScript.


Leave a Reply

Your email address will not be published.