Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akhileshdarjee/6d8dba5628408c0f871f3407d8014aeb to your computer and use it in GitHub Desktop.
Save akhileshdarjee/6d8dba5628408c0f871f3407d8014aeb to your computer and use it in GitHub Desktop.
Mouse move direction events in javascript
var last_position = {};
document.onmousemove = function(e) {
//check to make sure there is data to compare against
if (typeof(last_position.x) != 'undefined') {
//get the change from last position to this position
var deltaX = last_position.x - event.clientX,
deltaY = last_position.y - event.clientY;
//check which direction had the highest amplitude and then figure out direction by checking if the value is greater or less than zero
if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
// mouse move left
}
else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
// mouse move right
}
else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) {
// mouse move up
}
else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) {
// mouse move down
}
}
//set the new last position to the current for next time
last_position = {
x : event.clientX,
y : event.clientY
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment