Detect mouse direction - JavaScript

CRQ picture CRQ · Jun 18, 2014 · Viewed 16k times · Source
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.

Answer

adeneo picture adeneo · Jun 18, 2014

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