Home > Web Front-end > JS Tutorial > How Can I Track Mouse Position in JavaScript?

How Can I Track Mouse Position in JavaScript?

Linda Hamilton
Release: 2024-12-15 18:31:15
Original
258 people have browsed it

How Can I Track Mouse Position in JavaScript?

How to Track Mouse Position in JavaScript

Tracking the mouse position involves receiving events, such as mousemove, which report the coordinates of the mouse cursor. By handling these events, we can periodically retrieve and display the current position.

The following solution leverages the mousemove event attached to the window:

document.onmousemove = handleMouseMove;

function handleMouseMove(event) {
  var posX = event.pageX;
  var posY = event.pageY;

  console.log(`Current Position: ${posX}, ${posY}`);
}
Copy after login

Explanation:

  1. The onmousemove event listener is assigned to the document object, causing it to listen for mouse movements throughout the webpage.
  2. When a mousemove event occurs, the handleMouseMove function is executed.
  3. Inside the function, the event object is utilized to retrieve the mouse position using event.pageX and event.pageY.
  4. The obtained coordinates are then logged to the console, which you can view using the browser's JavaScript console.

Alternative Solution with Timer:

If you require a solution that periodically updates the mouse position, you can combine the above code with a timer function:

var mousePos;

document.onmousemove = handleMouseMove;
setInterval(getMousePosition, 100); // Update every 100ms

function handleMouseMove(event) {
  mousePos = {
    x: event.pageX,
    y: event.pageY,
  };
}

function getMousePosition() {
  if (!mousePos) {
    // Handle case where mouse position has not been set yet
  } else {
    // Use the stored mousePos.x and mousePos.y values
  }
}
Copy after login

Note: It's crucial to keep the processing within the event handler or timer function minimal to avoid overwhelming the browser. Consider optimizing your code by checking if the position has changed before performing complex calculations or updates.

The above is the detailed content of How Can I Track Mouse Position in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template