How to Track Mouse Movement with jQuery mousemove
Tracking mouse movement is an essential technique for creating
interactive web experiences, such as custom cursors, parallax effects,
and dynamic tooltips. This article explains how to capture real-time
cursor coordinates using jQuery's built-in .mousemove()
event listener. You will learn the basic syntax, how to extract X and Y
coordinates from the event object, and how to apply this to both the
entire document and specific DOM elements.
The jQuery mousemove() Method
The .mousemove() method in jQuery binds an event handler
to the mousemove JavaScript event. This event triggers
every time the user moves their mouse over the targeted element. To
capture movement across the entire screen, bind the event to the
$(document) object.
Accessing Mouse Coordinates
When the mousemove event fires, it passes an event
object to the callback function. This object contains properties
indicating the current position of the pointer:
event.pageX: The horizontal coordinate relative to the left edge of the entire document.event.pageY: The vertical coordinate relative to the top edge of the entire document.event.clientX: The horizontal coordinate relative to the visible viewport.event.clientY: The vertical coordinate relative to the visible viewport.
Implementation Example
Here is a straightforward example demonstrating how to track cursor coordinates and display them live in an HTML container:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Tracking</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#tracker-box {
width: 100%;
height: 250px;
background-color: #f0f0f0;
border: 2px dashed #999;
display: flex;
align-items: center;
justify-content: center;
font-family: sans-serif;
font-size: 1.2rem;
}
</style>
</head>
<body>
<div id="tracker-box">Move your mouse here</div>
<script>
$(document).ready(function() {
// Track movement over a specific element
$('#tracker-box').mousemove(function(event) {
let xPos = event.pageX;
let yPos = event.pageY;
$(this).text(`X: ${xPos}, Y: ${yPos}`);
});
});
</script>
</body>
</html>Tracking Across the Entire Window
If your goal is to track the mouse regardless of which element it
hovers over, attach the listener directly to
$(document):
$(document).mousemove(function(event) {
console.log(`Cursor position: ${event.pageX}, ${event.pageY}`);
});Performance Consideration
Because the mousemove event fires continuously at high
frequency, executing heavy DOM manipulations or complex calculations
inside the callback can cause performance issues and frame drops. When
building intensive features, consider using
requestAnimationFrame() or a throttling function to limit
the execution rate of your code.