magnus.dev
9/13/2013 - 12:24 PM

Javascript: Touch

Javascript: Touch

var touch = (function() {
	var config = function(options, element) {
		if(!options && !element) {
			return false;
		}

		if(options.disableClick === true) {
			element.onclick = function(e) {
				e.preventDefault();
			};
		}
		else if(options.disableClick === false) {
			element.onclick = null;
		}
	},

	getTouch = function(event) {
		return event.targetTouches ? event.targetTouches[0] : event;
	},

	touchstart = function(event) {
		var target = getTouch(event),
			touched = false;

		touch.start_x = touch.end_x = target.pageX;
		touch.start_y = touch.end_y = target.pageY;
		touch.target = target.target;

	},

	touchmove = function(event) {
		var target = getTouch(event);

		touch.end_x = target.pageX;
		touch.end_y = target.pageY;
	},

	touchend = function(event) {
		var typeOfTouch = null;

		if(touch.start_x === touch.end_x && touch.start_y === touch.end_y ) {
			typeOfTouch = 'tap';
		}
		else {
			typeOfTouch = 'swipe';
		}

		return typeOfTouch;
	},

	handleTap = function(element, func, options) {
		config(options, element);
		element.addEventListener('touchstart', touchstart);
		element.addEventListener('touchmove', touchmove);
		element.addEventListener('touchend', function(event) {
			if(options.propagation === true) {
				event.stopPropagation();
			}

			if(touchend(event) === 'tap') {
				func.call(undefined, touch.target, options);
			}
		});
	},

	handleSwipe = function(element, func, options) {
		config(options, element);
		element.addEventListener('touchstart', touchstart);
		element.addEventListener('touchmove', touchmove);
		element.addEventListener('touchend', function(event) {
			if(options.propagation === true) {
				event.stopPropagation();
			}

			if(touchend(event) === 'swipe') {
				func.call(undefined, touch.target, options);
			}
		});
	},

	handleSwipeLeft = function(element, func, options) {
		config(options, element);
		element.addEventListener('touchstart', touchstart);
		element.addEventListener('touchmove', touchmove);
		element.addEventListener('touchend', function(event) {
			if(options.propagation === true) {
				event.stopPropagation();
			}

			if(touchend(event) === 'swipe' && touch.start_x > touch.end_x) {
				func.call(undefined, touch.target, options);
			}
		});
	};

	return {
		start_x   : 0,
		start_y   : 0,
		end_x     : 0,
		end_y     : 0,
		target    : null,
		handleTap : handleTap,
		handleSwipe : handleSwipe,
		handleSwipeLeft : handleSwipeLeft
	};
}());

(function() {
	var element = document.querySelector('.navigation');

	touch.handleTap(element, function(target) {
		if(target.tagName === 'A') {
			console.info('[Tap]');
			target.classList.toggle('on');
		}
	}, {disableClick: true, propagation: true});

	touch.handleSwipeLeft(document, function(target) {
		console.info('[Swipe to the left]', touch.start_x, touch.end_x);
	}, {disableClick: true});
})();