Home >Web Front-end >JS Tutorial >How Can I 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}`); }
Explanation:
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 } }
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!