You can save the position of the last mousemove
event to compare to the current position:
//setup a variable to store our last position
var last_position = {},
$output = $('#output');
//note that `.on()` is new in jQuery 1.7 and is the same as `.bind()` in this case
$(document).on('mousemove', function (event) {
//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) {
//left
} else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
//right
} else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) {
//up
} else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) {
//down
}
}
//set the new last position to the current for next time
last_position = {
x : event.clientX,
y : event.clientY
};
});
Here is a demo: http://jsfiddle.net/Dv29e/
Update
You can also throttle the mousemove
event to get more of a general idea where the mouse has moved:
var last_position = {},
$output = $('#output'),
mousemove_ok = true,
mouse_timer = setInterval(function () {
mousemove_ok = true;
}, 500);
$(document).on('mousemove', function (event) {
if (mousemove_ok) {
mousemove_ok = false;
...
}
});
This will only check the cursor's position against it's past position if:
- the last position exists.
- the
mousemove_ok
variable is set to true
which is done every half second.
Here is a throttled demo: http://jsfiddle.net/Dv29e/4/