Detect mouse direction - JavaScript
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);
This code will give you the 'direction' of 'X' and 'Y' in directionX and direction Y variable and the distance traveled by 'X' and 'Y' axis.
let oldX = 0, oldY = 0;
function captureMouseMove($event){
let directionX = 0, directionY = 0, diffX = 0, diffY = 0;
if ($event.pageX < oldX) {
directionX = "left"
diffX = oldX - $event.pageX;
} else if ($event.pageX > oldX) {
directionX = "right"
diffX = $event.pageX - oldX;
}
if ($event.pageY < oldY) {
directionY = "top"
diffY = oldY - $event.pageY;
} else if ($event.pageY > oldY) {
directionY = "bottom";
diffY = $event.pageY - oldY;
}
oldX = $event.pageX;
oldY = $event.pageY;
}
window.addEventListener('mousemove', captureMouseMove);
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