XCS
XCS

Reputation: 28137

jQuery mousemove() is called even if the mouse is still

For me, if I try this example: http://jsfiddle.net/bY3CC/3/ the "mouse moved" text appears even if I move my mouse over the document and then I let it still...

Why's that? ;\

And also, seems like the message only appears in Chrome....

Strange :-s

Upvotes: 11

Views: 5792

Answers (2)

user2106480
user2106480

Reputation: 181

Store the x, y co-ordinates

$(document).mousemove((function(){
    var x,y;

    return function(evt){
        if(evt.clientX == x && evt.clientY == y){
            return;
        }
        x = evt.clientX;
        y = evt.clientY;
        $('#messages').append('mouse moved<br/>');
    };
})());

Upvotes: 11

Guffa
Guffa

Reputation: 700232

The global event object is non-standard, so it only exists in some browsers, like IE (perhaps only in quirks mode) and appearently in Chrome.

Accept the event object as a parameter to the event handler:

var last_moved=0;
$(document).mousemove(function(e){
  var now = e.timeStamp;    
  if (now - last_moved > 1000) {
    $('#messages').append('mouse moved<br/>');
    last_moved = now;
  }
});

jsfiddle.net/bY3CC/5/

Upvotes: 4

Related Questions