Skip to content
Advertisement

Track mouse speed with JS

What’s the best way to track the mouse speed with plain JS/JQuery? I’d like to track how fast a user moves the mouse in all directions (up/down/left/right).

Advertisement

Answer

Sparklines has a nifty example of tracking mouse movement and graphing it. Their code is available in the source of their site starting at line 315.

Simple and effective.

Here is the code:

 var mrefreshinterval = 500; // update display every 500ms
 var lastmousex=-1; 
 var lastmousey=-1;
 var lastmousetime;
 var mousetravel = 0;
 $('html').mousemove(function(e) {
     var mousex = e.pageX;
     var mousey = e.pageY;
     if (lastmousex > -1)
         mousetravel += Math.max( Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey) );
     lastmousex = mousex;
     lastmousey = mousey;
 });
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement