Search code examples
javascriptmouseeventmousemousemove

Detect mouse real direction


My goal is to detect the direction of the last mouse movement before the mouseup event trigger.

To avoid validating small involuntary movements (ex: I go with the mouse to the right for 100px and then I stop but involuntarily do 2px to the left) I would confirm the direction only after the mouse pointer has achieved a minimum safety distance (gap) from the last point where it has reversed its direction.

Here is a simplification of my implementation:

var direction = "",
oldx = 0,
invert = 0,
gap = 10,
move = "",
mousemovemethod = function (e) {

    if (e.pageX < oldx) {
        if(direction == "right") invert = e.pageX;
        direction = "left";
        if(e.pageX < invert - gap) move = "left";
    } else if (e.pageX > oldx) {
        if(direction == "left") invert = e.pageX;
        direction = "right"
        if(e.pageX > invert + gap) move = "right";
    }

    document.body.innerHTML = "moving " + direction + ", last inversion point: " + invert + ", Validated movement: " + move;

    oldx = e.pageX;

}

document.addEventListener('mousemove', mousemovemethod);

And here is a fiddle

The code works but it seems to me verbose and unclear. I have always been poor in this kind of implementation and I was wondering if anyone knew a more elegant way of handling this mechanics.

Every suggestion is welcome.


Solution

  • function smooth(){
        var direction="",
        oldx = 0,
        noise=10,
        dir=0;
        mousemove=function(e){
           dir=oldx-e.pageX;
           if(Math.abs(dir)> noise){
              (dir <=0 )?direction="right":direction="left";
              oldx=e.pageX;
           }
           document.body.innerHTML = "moving " + direction;
       };
       document.addEventListener('mousemove', mousemove);
    }
    

    How about this?