Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect mouse direction - JavaScript

var direction = ""
var mousemovemethod = function (e) {
    var oldx = 0;
    if (e.movementX < oldx) {
        direction = "left"
    } else if (e.movementX > oldx) {
        direction = "right"
    }
    oldx = e.pageX;
}

This is how I detect the mouse direction and it works so good but it works only on Chrome, how I can make this compatible with other browsers (Firefox, Opera and at least ie8+ or ie9+). No jQuery please.

like image 866
CRQ Avatar asked Jun 18 '14 20:06

CRQ


2 Answers

Stick with pageX and define oldx in a higher scope, otherwise it's always zero

var direction = "",
    oldx = 0,
    mousemovemethod = function (e) {

        if (e.pageX < oldx) {
            direction = "left"
        } else if (e.pageX > oldx) {
            direction = "right"
        }

        oldx = e.pageX;

}

FIDDLE

like image 87
adeneo Avatar answered Nov 03 '22 07:11

adeneo


on mouse move - to left, to right, to up, to down - javascript FIDDLE

var direction = "";
    var oldx = 0;
    var oldy = 0;
    mousemovemethod = function (e) {
    
 if (e.pageX > oldx && e.pageY == oldy) {
                direction="East";
            }
            else if (e.pageX == oldx && e.pageY > oldy) {
                direction="South";
            }
            else if (e.pageX == oldx && e.pageY < oldy) {
                direction="North";
            }
            else if (e.pageX < oldx && e.pageY == oldy) {
                direction="West";
            }
        
        document.body.innerHTML = direction;
        
        oldx = e.pageX;
         oldy = e.pageY;
        
}

document.addEventListener('mousemove', mousemovemethod);
like image 20
Thangaraj Avatar answered Nov 03 '22 07:11

Thangaraj