Bind/Unbind Mouse Move, Direction Keys and Touch Swipe events from JavaScript

1. Touch Swipe Events for Touch Devices

var xDown = null;
var yDown = null;
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);

function handleTouchStart(evt) {
    xDown = evt.touches[0].clientX;
    yDown = evt.touches[0].clientY;
};

function handleTouchMove(evt) {
    if (!xDown || !yDown) {
        return;
    }

    var xUp = evt.touches[0].clientX;
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if (Math.abs(xDiff) > Math.abs(yDiff)) {
        if (xDiff > 0) {
        // swipe right direction
        }
        else {
        // swipe left direction
        }
    }
    else {
        if (yDiff > 0) {
        // swipe down direction
        }
        else {
        // swipe up direction
        }
    }

    /* reset values */
    xDown = null;
    yDown = null;
};

Unbind event:

$('body').unbind('touchmove');

2. Direction Arrow Keys Binding

// set key binding for direction arrows
$(document).keydown(function(e) {
    switch(e.which) {
        case 37:
        // left direction
        break;

        case 38:
        // up direction
        break;

        case 39:
        // right direction
        break;

        case 40:
        // down direction
        break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
});

Unbind event:

$(document).unbind('keydown');

3. Mouse move direction events

var last_position = {};

$(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) {
            // 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
    };
});

Unbind event:

$(document).off('mousemove');