Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 445
XCS Avatar asked Jan 02 '11 15:01

XCS


People also ask

How does MouseMove work?

MouseMove is a simple event that is executed when a pointer is moving over or around an element. Mousemove is a javascript event that inside a web page. The mousemove event can also be understood as a part of an event handler, whereupon some action or movement by a mouse pointer, an intended script is executed.

What is MouseMove Javascript?

Definition and Usage. The onmousemove event occurs when the pointer is moving while it is over an element.

What is the difference between mouseover and Mouseenter?

The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element. The onmousemove event triggers every time the mouse pointer is moved over the div element.

Which event is used when mouse moves over the element?

The mouseover event is fired at an Element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.


2 Answers

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/>');
    };
})());
like image 171
user2106480 Avatar answered Sep 22 '22 11:09

user2106480


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/

like image 39
Guffa Avatar answered Sep 23 '22 11:09

Guffa