1
var timer;
var stoppedElement=document.getElementById("stopped");   // store element for faster access

function mouseStopped(){                                 // the actual function that is called
    stoppedElement.innerHTML="Mouse stopped";
}

window.addEventListener("mousemove",function(){
    stoppedElement.innerHTML="Mouse moving";
    clearTimeout(timer);
    timer=setTimeout(mouseStopped,300);
});

This fiddle detect the mouse move but when moving the mouse wheel it said that mouse is moving, can we separate between move and wheel events ?

albert
  • 8,112
  • 3
  • 47
  • 63
ahmad soliman
  • 141
  • 1
  • 2
  • 14

1 Answers1

1

In addition to scroll events, Webkit browsers fire mousemove events, since the cursor can be in a different position after the scrolling.

The solution is to manually check, whether the position changed, or not:

var timer;
var stoppedElement=document.getElementById("stopped");   // store element for faster access

function mouseStopped(){                                 // the actual function that is called
    stoppedElement.innerHTML="Mouse stopped";
}

window.addEventListener("mousemove",function(e){
    if ((window.lastX !== e.clientX && window.lastX !== undefined)
        || (window.lastY !== e.clientY && window.lastY !== undefined)) {
        stoppedElement.innerHTML="Mouse moving";
        clearTimeout(timer);
        timer=setTimeout(mouseStopped,300);
    }   
    window.lastX = e.clientX
    window.lastY = e.clientY
})    
<div id="stopped"></div>
ArtBIT
  • 3,931
  • 28
  • 39