How to Get Mouse Coordinates in Javascript

In this tutorial, you will learn how to get mouse coordinates in javascript. As you already know, the mouse and keyboard play a very important role in the user interaction on a webpage. In a webpage, we have vertical and horizontal coordinates and that thing makes it easy to grab the exact position of the mouse pointer.

Any user interaction on a webpage triggers certain events. Since we are looking for the position of the mouse pointer, we will only cover click and mousemove events.  The click event occurs whenever a user clicks on an element.  The mousemove event is fired whenever the mouse pointer moves within an element.

In the case of both the above events, we will have pageX and pageY properties in the event object. The pageX property will give us horizontal coordinates and the pageY property will give us vertical coordinates.  For the sake of simplicity, we are going to get the position of the mouse pointer whenever we click or move anywhere in the document.

You can also go with clientX and clientY properties to get mouse coordinates.  But there is a difference between page and client coordinates. The page represents the whole rendered page and that includes the visible area as well as scrolled area in the browser. On the other hand, the client will only give you coordinates based on the visible area in the browser.

In the following example, we will simply display horizontal and vertical coordinates of the mouse pointer on click and movement. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have an empty div element with a style attribute to center align text content horizontally. The text content will contain mouse coordinates and it will be updated dynamically using javascript.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="output" style="text-align: center"></div>

    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have selected the div element using the document.querySelector() method and stored it in the output variable.
  • We have attached click and mousemove event listeners to the document.
  • In both the event handler functions, we are using pageX and pageY properties to get horizontal and vertical coordinates respectively.
  • We are displaying those mouse coordinates in the div element using the innerText property.
let output = document.querySelector('#output');

document.addEventListener('click', (e) => {
    output.innerText = `X: ${e.pageX} - Y: ${e.pageY}`;
});


document.addEventListener('mousemove', (e) => {
    output.innerText = `X: ${e.pageX} - Y: ${e.pageY}`;
});