'Capture mouse position on setInterval() in Javascript

I have a function in Javascript that moves one div depending on the mouse position. This function is set on a setInterval() function and executed every second. I need to capture the mouse position like this:

function mousemov() {
  document.getElementById("myDiv").style.left = Event.clientX; //don't work
}

window.onload = function() {
  setInterval("mousemov()",1000);
}

Ps: I cannot use the mousemove event because the function must be executed even if the mouse is stopped.



Solution 1:[1]

well, if you listen to mouse move for the document and save its location, then, whenever you want, e.g. every second in your case you have the latest registered mouse position.

this is a jquery example

$(document).ready(function()
 {
  $().mousemove(function(e)
   {
       window.mouseX = e.pageX;
       window.mouseY = e.pageY;
  });
});

and your mousemove function would be

function mousemov() { 
    document.getElementById("myDiv").style.left = window.mouseX;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tzury Bar Yochay