Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get cursor position on setInterval() callback

I need to record the mouse position every n seconds, but jQuery seems to only offer ways to retrieve the x and y position values when there is a mouse event. Can this be done with setInterval()?

EDIT - I'm thinking to set a setInterval() to increase a value every n seconds (say 'i'), and then on mousemove record the current i alongside the x and y values. There really should be an easier way than this though

like image 310
Voriki Avatar asked Jul 16 '26 16:07

Voriki


2 Answers

What you can do is bind a function to the mousemove event on the document, and inside the function set a global variable with the mouse position. then every interval you can read the mouse position.

example:

$(document).ready(function () {
    var mousePosition = {'x': 0, 'y': 0};
    $(document).bind('mousemove', function(e) {
        mousePosition = {'x': e.pageX, 'y': e.pageY};
    });

    setInterval(function () {
        // do something with mousePosition
    }, 1000);
});
like image 56
jeffreydev Avatar answered Jul 19 '26 06:07

jeffreydev


This should help.

http://jsbin.com/owifu3/

http://docs.jquery.com/Tutorials:Mouse_Position

Might as well paste the code...

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 
})
</script>
<body>
<h2 id="status">
0, 0
</h2>
</body>
</html>
like image 20
Derek Avatar answered Jul 19 '26 06:07

Derek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!