JavaScript for Capturing mouse positions after every given interval Last Updated : 07 Jun, 2023 Comments Improve Suggest changes Like Article Like 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”. Comment More infoAdvertise with us Next Article JavaScript for Capturing mouse positions after every given interval S ShubhamTyagi Follow Improve Article Tags : JavaScript Web Technologies javascrpt-input JavaScript-Questions Similar Reads How to Detect Idle Time in JavaScript ? The idle time is the time that the user doesn't interact with a web page. This interaction can be either moving the mouse, clicking on the page, or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time. \ Method 1: Using Ja 4 min read How to differentiate mouse âclickâ and âdragâ event using JavaScript ? Working with web elements a user may drag or click an element as per requirement. It is important to distinguish between drag and click events. JavaScript is a high-level, dynamically typed programming language that can be used to distinguish between drag and click events. JavaScript has drag-and-cl 3 min read How to make animated counter using JavaScript ? Creating an animated counter with JavaScript is an easy way to make your website more interactive. It smoothly increases or decreases numbers, which is great for displaying stats or other dynamic content. You can easily customize the speed and timing using HTML, CSS, and JavaScript.Approach :Making 3 min read JavaScript Coordinates of Mouse In JavaScript, we have methods that help us to capture the location of the mouse on the screen. The top left corner of the screen is (0, 0) i,e, X, and Y coordinates are (0, 0). This means that vertical zero is the topmost point and horizontal zero is the leftmost point. In this article, we are goin 2 min read JavaScript Call a function after a fixed time In order to run a function multiple times after a fixed amount of time, we are using few functions. JavaScript setInterval() MethodThis method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed. Synta 3 min read How to find the position of HTML elements in JavaScript ? In this article, we are given an HTML document and the task is to get the position of any element by using JavaScript. Use the following steps to get the position: Step 1: Selecting an element: Before finding the position, it is necessary to select the required HTML element. Every element in HTML is 3 min read How to Change Background Color According to Mouse Location using JavaScript? To change the background color based on the mouse location in JavaScript, we can track the cursor's position on the screen and adjust the background color as the mouse moves. This is done by capturing the X and Y coordinates of the mouse and applying those values to change the background color dynam 1 min read Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to 5 min read How to Determine which Element the Mouse Pointer Move Over using JavaScript? Given an HTML document and the task is to get the element where the mouse pointer moves over. Below are the approaches to Determining which Element the Mouse Pointer moves over using JavaScript: Table of ContentUsing clientX and clientY propertiesUsing onmouseover propertyApproach 1: Using clientX a 2 min read How to Map Mouse Position in CSS? This article will describe how to map the position of the mouse on the web page using CSS. You can do this in CSS using:hover pseudo-class and custom properties that contain the relative position of the mouse and change accordingly with:hover.Approach: To map the position of the mouse, we will maint 8 min read Like