Open In App
Related Articles

JavaScript for Capturing mouse positions after every given interval

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The JavaScript language was initially created for web browsers. Since then, it evolved and became a language with many uses and platforms. It lets us interact with the browser using events. Events are signals that something has happened. When JavaScript is used in HTML pages, JavaScript can react to these events. To react to events we can assign a handler – a function that runs in case of an event. Handlers are a way to run JavaScript code in case of user actions.

In this article, we will be focusing on how to capture mouse positions on an empty HTML page in a time period of 10 seconds within a given interval of time. The page will be initially empty. On the first click, a timer of 10 seconds will start and on ending the start time and the X and Y-coordinates of mouse positions will be displayed in the form of a JavaScript object. The event handlers we will be using for this task will be: 

  • movemouse: When the cursor of the mouse is moved. 
  • DOMContentLoaded: When the HTML is loaded and processed. DOM is fully built. Here is the JavaScript program for the same.

Example:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>
        JavaScript for Capturing Mouse Positions
        After Every Given Interval
    </title>
</head>
 
<body>
    <div id="timer-section" style="text-align: center;">
        Timer will appear here!
    </div>
 
    <div id="output-section"></div>
 
    <script type="text/javascript">
 
        // Timer
        let limit = 10000;
 
        // Time interval of 500 millisecond set
        let throttle = 500;
 
        // Timer is off initially
        let timerON = false;
        let start;
        let last;
        let mousePositions = [];
 
        // Records the time when the timer starts
        function makeTime(s) {
            return s.getHours() + " : " + s.getMinutes()
                + " : " + s.getSeconds();
        }
 
        // When the first click to start the timer,
        // this function will get envoked
        function clickEnvoke() {
            start = (new Date).getTime();
            mousePositions.push({
                time: {
                    start: makeTime(new Date())
                }
            });
            console.log(mousePositions);
            last = (new Date).getTime();
            let time = 10;
 
            // Timer has started
            timerON = true;
            document.removeEventListener('click', clickEnvoke);
            document.addEventListener('mousemove', mouseUpdate);
            let timer = setInterval(function () {
                if (time >= 0)
                    document.getElementById('timer-section')
                        .innerHTML = time;
                else {
 
                    // Mouse positions will be stop recording
                    // as timer is 0
                    timerON = false;
                    clearInterval(timer);
                    document.removeEventListener('mousemove', mouseUpdate);
 
                    // JSON data need to converted into
                    // string to print as object
                    document.getElementById('timer-section').innerHTML = "";
                    document.getElementById('timer-section').innerHTML +=
                        JSON.stringify(mousePositions);
                }
 
                time--;
            }, 1000);
        }
 
        // Capturing mouse positions envoked
        function mouseUpdate(event) {
            let now = (new Date).getTime();
            if (timerON) {
                if (now - start > limit) {
                    return document.removeEventListener(
                            'mousemove', mouseUpdate);
                }
 
                if (now - last < throttle) {
                    return;
                }
                last = now;
                mousePositions.push({
                    info: {
                        x: event.pageX,
                        y: event.pageY
                    }
                });
 
            }
            else
                console.log(mousePositions);
            // Do whatever you want to do within your
            // time limit here
        }
 
        // Initial HTML page is empty and DOM is loaded
        // upon first click our functions will work
        document.addEventListener('DOMContentLoaded', function () {
            let loadTime = (new Date).getTime();
            document.addEventListener('click', clickEnvoke);
        });
    </script>
</body>
</html>

                    

Output:

 

Note: We have to keep on moving the mouse cursor as soon as the timer starts else we may not get a number of coordinates as desired. We will learn about more event handlers and related problems in the coming articles on “Using JavaScript to interact with the browser”.



Last Updated : 07 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads