CancelImage Upload

How to load the current mouse coordinates or location with JavaScript

Every day the demand on web applications increases, requiring them to look and feel more and more like a windows desktop environment. Achieving these effects requires the use of JavaScript event functions.

An event in JavaScript is every time a specific action happens that interacts with user input systems, such as the mouse and keyboard. In the example on this page we will use the event onmousemove, which calls upon or carries out a defined JavaScript command every time the user moves the mouse inside the browser environment. Through this even we will call upon a function we shall call load_coordinates(), which will do just as the name indicates.

To load the two coordinates we will use the following two lines of code. Through the event object, the variable clientX and clientY will return the current x and y coordinates of our mouse:

x = event.clientX;

y = event.clientY;

By regularly loading the above to variables into a span tag, we have built ourselves a simple mouse tracking script:

<html>
<head>
<title>How to load the current mouse coordinates or location with JavaScript</title>
<script language="javascript">

function load_coordinates(event)
{

        x = event.clientX;

        y = event.clientY;

        var location = document.getElementById("location");

        location.innerHTML = "X: " + x + "<br>Y: " + y;

}

</script>
</head>
<body onmousemove="load_coordinates(event)">

<span id="location"></span>

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com