# Calculate the distance between mouse and element in jQuery

In this tutorial type post, we are going to calculate the distance between mouse and an element. We are going to measure the distance of mouse cursor from the element and show it on our web page using jQuery.

To get the distance between mouse and the element we are going to use the jQuery mousemove event listener.

Now we are going to see the example code.

At first, let’s write our HTML code:

```<center>
<div id="MyEl"></div>
<h2>Distance: <span id="el-distance">0</span>px</h2>
</center>
```

The above HTML code contains the element and also contains the text that will show the distance of mouse from the element soon.

```#MyEl {
background-color: red;
height: 35px;
width: 35px;
margin-top: 200px;
}```

If you run the code, you will see the red ball on the screen. It will not do anything and not be going to tell you the distance of mouse from the red ball in the time of moving it.

After adding the below jQuery JavaScript code it should work:

```var mouseX, mouseY, el_distance,
\$el_distance = \$('#el-distance'),
\$my_el  = \$('#MyEl');

\$(document).mousemove(function(event) {
mX = event.pageX;
mY = event.pageY;
el_distance = measureDistance(\$my_el, mX, mY);
\$el_distance.text(el_distance);
});

function measureDistance(my_element, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (my_element.offset().left+(my_element.width()/2)), 2) + Math.pow(mouseY - (my_element.offset().top+(my_element.height()/2)), 2)));
}

```

In the above jQury code, we have used the jQuery mousemove event listener event to get the position of the mouse cursor. After that, in another function, we are calculating the distance between mouse cursor and the element from the position of the element and mouse.

### Complete and final code to get the distance between mouse and the element

Now below is the complete and final HTML code:

```<!DOCTYPE html>
<html>
<title></title>

<style type="text/css">
#MyEl {
background-color: red;
height: 35px;
width: 35px;
margin-top: 200px;
}
</style>
<body>

<center>
<div id="MyEl"></div>
<h2>Distance: <span id="el-distance">0</span>px</h2>
</center>

<script type="text/javascript">

var mouseX, mouseY, el_distance,
\$el_distance = \$('#el-distance'),
\$my_el  = \$('#MyEl');

\$(document).mousemove(function(event) {
mX = event.pageX;
mY = event.pageY;
el_distance = measureDistance(\$my_el, mX, mY);
\$el_distance.text(el_distance);
});

function measureDistance(my_element, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (my_element.offset().left+(my_element.width()/2)), 2) + Math.pow(mouseY - (my_element.offset().top+(my_element.height()/2)), 2)));
}

</script>
</body>
</html>```

If we run the code on our browser, we will see a red circle or ball and the text below which show the distance between the element and mouse and it will change with the change of mouse cursor position.

I hope you find this tutorial interesting.