JavaScript Coordinates of Mouse

In JavaScript, we have methods that help us to capture the location of the mouse on the screen. The top left corner of the screen is (0, 0) i,e, X, and Y coordinates are (0, 0). This means that vertical zero is the topmost point and horizontal zero is the leftmost point. In this article, we are going to learn how to find the Coordinates of the Mouse cursor in JavaScript.

It can be implemented using the clientX and clientY methods of the event: 

  • event.clientX: It gives the horizontal coordinate of the event.
  • event.clientY: It gives the vertical coordinate of the mouse.

Syntax: 

// For X coordinate
event.ClientX
// For Y coordinate
event.ClientY

Approach

  • 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: Below is the implementation of the above approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<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 onmousemove="coordinate(event)">
    X-coordinate
    <input type="text" id="X">
    <br>
    <br>
    Y-coordinate
    <input type="text" id="Y">
</body>
 
</html>


Output: