Tutorialspoint.dev

JavaScript for Capturing mouse positions after every given interval

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 browser using events. Events are signals that something has happened. When JavaScript is used in HTML pages, JavaScript can react on these events. To react on 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 will of 10 seconds will start and on ending the start time and the X and Y-coordinates of mouse positions will be displayed in form of JavaScript object.

The event handlers we will be using for this task will be:

1. movemouse: When the cursor of the mouse is moved.
2. DOMContentLoaded: When the HTML is loaded and processed. DOM is fully built.

Here is the JavaScript program for the same:

<html>
  
<head>
    <title>Timer Demo</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
var limit = 10000; 
  
// time interval of 500 millisecond set
var throttle = 500;     
  
//timer is off initially
var timerON = false;                 
var start ;
var last ;
var 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();
    var time = 10;
      
    // timer has started
    timerON = true;                 
    document.removeEventListener('click', clickEnvoke);
    document.addEventListener('mousemove', mouseUpdate);
    var 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) {
  var 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 () {
    var loadTime = (new Date).getTime();
    document.addEventListener('click', clickEnvoke);
});
</script>
</body>
</html>                    

NOTE: We have to keep on moving the mouse cursor as soon as the timer starts else we may not get 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”.



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter