Get Coordinates of Mouse on Web Page in JavaScript.

In this tutorial, we will see how to get coordinates of mouse on web page in JavaScript.

Mouse coordinates refer to the position of the mouse cursor on a computer screen, typically measured in terms of X and Y coordinates. These coordinates provide information about the location of the mouse relative to the screen or a specific element within a web page or application.

In this example :
  • we have HTML structure with head, meta tags, and script for JavaScript.
  • JavaScript function coordinate(event) captures mouse coordinates using event.clientX and event.clientY.
  • The function updates input fields with IDs “X” and “Y” using document.getElementById.
  • onmousemove the attribute in the body triggers the coordinate function on mouse movement.
  • Display X and Y coordinates in real-time using input fields with IDs “X” and “Y” in the HTML body.
Example: 
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<script>
    function coordinate(event) {
        let x = event.clientX;
        let y = event.clientY;
        document.getElementById("X").value = x;
        document.getElementById("Y").value = y;
    }
</script>

<body mousemove="coordinate(event)">
    X-coordinate
    <input type="text" id="X">
    <br>
    <br>
    Y-coordinate
    <input type="text" id="Y">
</body>

</html>

Output:

Leave a Comment

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

Scroll to Top