JavaScript example for Capturing mouse positions after every given interval

In this article, we will demonstrate how to capture the mouse position in JavaScript at regular intervals and log or use this data for various purposes. Capturing mouse positions after every given interval refers to a program or functionality where the current position of the mouse pointer is tracked at regular time intervals. This can be useful in scenarios like debugging, interactive applications, or visualizing user movement on a web page.

Use Cases

Imagine you want to monitor user activity on a web page and record the mouse position every second. This can be useful for:

  • Analytics: Tracking how users navigate or interact with different page areas.
  • Games and Simulations: Capturing user input for animations or gameplay.
  • Heatmaps: Visualizing user behavior on a webpage.

How It Works

JavaScript provides tools like the mousemove event to capture real-time mouse movements. Combining this with setInterval allows you to log the mouse position at specified intervals.

The mousemove event is used to detect when the mouse pointer moves within the webpage:

document.addEventListener('mousemove', (event) => {
    mouseX = event.clientX; // Get the X-coordinate
    mouseY = event.clientY; // Get the Y-coordinate
});

The event listener attached to mousemove captures the mouse's current position (clientX and clientY) in real-time.

Complete Example

Here's a complete example that captures mouse positions every 3 seconds after clicking a button:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mouse Position Capture</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: blueviolet;
            margin: 20px 0;
        }
        .btn {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <h1>Capture Mouse Position Every 3 Seconds</h1>
    <div class="result">Move your mouse and click the button to start tracking</div>
    <button class="btn">START TRACKING</button>
    
    <script>
        let resultEle = document.querySelector(".result");
        let xCoord = 0, yCoord = 0;
        let tracking = false;
        
        // Capture mouse position continuously
        document.body.addEventListener("mousemove", function (event) {
            xCoord = event.clientX;
            yCoord = event.clientY;
        });
        
        // Function to display coordinates
        function displayCoordinate() {
            if (tracking) {
                resultEle.innerHTML = 
                    "X coordinate = " + xCoord + "<br> Y coordinate = " + yCoord;
                console.log(`Mouse Position: X=${xCoord}, Y=${yCoord}`);
            }
        }
        
        // Start tracking on button click
        document.querySelector(".btn").addEventListener("click", () => {
            tracking = true;
            setInterval(displayCoordinate, 3000);
        });
    </script>
</body>
</html>

Different Interval Examples

You can adjust the interval in setInterval to capture positions more or less frequently:

// Every 500ms (0.5 seconds)
setInterval(() => {
    console.log(`Mouse Position: X=${mouseX}, Y=${mouseY}`);
}, 500);

// Every 1 second
setInterval(() => {
    console.log(`Mouse Position: X=${mouseX}, Y=${mouseY}`);
}, 1000);

// Every 5 seconds
setInterval(() => {
    console.log(`Mouse Position: X=${mouseX}, Y=${mouseY}`);
}, 5000);

Key Points

  • The mousemove event captures mouse coordinates in real-time
  • event.clientX and event.clientY provide viewport-relative coordinates
  • setInterval allows periodic execution at specified time intervals
  • Store coordinates in variables to access them outside the event handler

Output

Mouse Position: X=245, Y=123
Mouse Position: X=312, Y=87
Mouse Position: X=156, Y=234

Conclusion

By combining JavaScript's mousemove event and setInterval, you can easily track and capture mouse positions at specified intervals. This approach is flexible and perfect for analytics, games, or interactive web experiences.

Updated on: 2026-03-15T23:18:59+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements