get the mouse position javascript

Get the Mouse Position in JavaScript

If you want to retrieve the mouse position using JavaScript, you can use the mouse events to track the mouse movement and get the position of the cursor relative to the document or an element on the page.

Using the mousemove event

To get the current position of the mouse cursor, you can add an event listener for the 'mousemove' event and retrieve the x and y coordinates of the cursor from the 'clientX' and 'clientY' properties of the event object:

const target = document.querySelector('#target');

target.addEventListener('mousemove', (event) => {
  const mouseX = event.clientX;
  const mouseY = event.clientY;
  console.log(`Mouse position: (${mouseX}, ${mouseY})`);

The code above adds an event listener to an element with an ID of 'target' and logs the mouse position to the console on every mouse movement within that element.

Using the offset from an element

If you want to get the position of the mouse cursor relative to a specific element on the page, you can subtract the element's offset from the mouse coordinates:

const box = document.querySelector('#box');

box.addEventListener('mousemove', (event) => {
  const rect = box.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY -;
  console.log(`Mouse position in box: (${mouseX}, ${mouseY})`);

In this example, we are retrieving the bounding rectangle of the element and subtracting its left and top offsets from the mouse coordinates to get the position relative to the element.

You can use this method to track the mouse position within a canvas or an SVG element.

Using the pageX and pageY properties

The 'pageX' and 'pageY' properties of the mouse event object also provide the position of the cursor relative to the top-left corner of the entire document:

document.addEventListener('mousemove', (event) => {
  const mouseX = event.pageX;
  const mouseY = event.pageY;
  console.log(`Mouse position: (${mouseX}, ${mouseY})`);

This code listens for the 'mousemove' event on the entire document and logs the mouse position relative to the document.

Regardless of which method you choose, you can use the retrieved mouse position information in your scripts to create interactive elements or animations that respond to user input on your web pages.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]