11

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

XCS
  • 27,244
  • 26
  • 101
  • 151

2 Answers2

11

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/>');
    };
})());
user2106480
  • 181
  • 1
  • 5
4

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/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Ok, that solved half of the problem. Now, why's the message appearing if if the mouse is still? – XCS Jan 02 '11 at 15:47
  • I don't have Chrome installed right now, but I have tested this in Firefox 3, IE 9, Opera 11 and Safari 4, and they don't trigger the event when the mouse is still. Perhaps Chrome does something odd, or perhaps you have some plugin or something that could cause this? – Guffa Jan 02 '11 at 16:08
  • It also happens on my Chrome installation (9.0.597.19 beta). Oddly, printing the current mouse pixel position shows it's always at the same position. – AbdullahC Jan 02 '11 at 16:26
  • This is odd, after restarting Chrome, it worked perfectly... Here is what I was working at anyway :D http://bit.ly/hRpiqr – XCS Jan 02 '11 at 20:33
  • @Guffa why when you click on the document it shows the message too? the mouse still at the same position? – msm.oliveira Jun 04 '15 at 14:16
  • @msm.oliveira: Because you are actually moving the mouse a little bit when clicking. It's possible to click without moving the mouse at all, but it's not easy. Note that a mouse movement may be too small to move the mouse pointer a pixel, but it's still registered as a movement. – Guffa Jun 04 '15 at 14:49