bcarasco
11/30/2012 - 7:08 PM

jQuery swiping - without a plugin

jQuery swiping - without a plugin

var touchStartLocation, touchEndLocation;
var touchID;
var startTime, endTime;
var timeThreshold = 500;
var distanceThreshold = 20;
			
$('#element').on('mousedown.swipeEvent touchstart.swipeEvent', function (e) {
	if (e.type == 'touchstart') {
		touchStartLocation = {
			x: e.originalEvent.touches[0].pageX,
			y: e.originalEvent.touches[0].pageY
		};
		touchID = e.originalEvent.touches[0].identifier;
	} else {
		touchStartLocation = {
			x: e.originalEvent.pageX,
			y: e.originalEvent.pageY
		};
	}
				
	startTime = new Date().getTime();
				
	return false;
});
			
$('#element').on('mouseup.swipeEvent touchend.swipeEvent touchcancel.swipeEvent', function (e) {
	var $this = $(this);

	if (e.type !== 'touchcancel') {
		if (e.type == 'mouseend') {
			touchEndLocation = {
				x: e.pageX,
				y: e.pageY
			};
		} else {
			for (var i=0; i < e.originalEvent.changedTouches.length; i++) {
				var t = e.originalEvent.changedTouches[i];
							
				if (t.identifier == touchID) {
					touchEndLocation = {
						x: t.pageX,
						y: t.pageY
					}
					break;
				}
			};
		}
						
		e.preventDefault();
					
		endTime = new Date().getTime();
					
		// If the swipe took too long
		if (endTime - startTime > timeThreshold) return false;
					
		if (Math.abs(touchStartLocation.x - touchEndLocation.x) > distanceThreshold && Math.abs(touchStartLocation.y - touchEndLocation.y) < distanceThreshold) {
			// The swipe was vertical
			if (touchStartLocation.x > touchEndLocation.x) $this.trigger('swipeLeft');
			else $this.trigger('swipeRight');
		} else if (Math.abs(touchStartLocation.x - touchEndLocation.x) < distanceThreshold && Math.abs(touchStartLocation.y - touchEndLocation.y) > distanceThreshold) {
			// The swipe was horizontal
			if (touchStartLocation.y > touchEndLocation.y) $this.trigger('swipeUp');
			else $this.trigger('swipeDown');
		}
	}
});
			
$('#element').on('swipeUp swipeRight swipeLeft swipeDown', function (e) {
	console.log(e.type);
});