kobaatsu
8/25/2012 - 9:22 AM

add-touch-event.js

add-touch-event.js

/**
 * add-touch-event.js
 * Version 0.1
 *
 * Copyright 2012, Yoshihito Fujiwara
 * MIT License.
 *
 *
 * Date: 2012-08-25
 * Author: Yoshihito Fujiwara
 *
 *
 * Capable Browser
 * Android Browser 2.3 later
 * iOS safari4.1 later 
 *
 *
 */


Object.prototype.touchEvent = function(f){
	this.addEventListener('touchstart', f, false);
	this.addEventListener('touchend', f, false);
	this.addEventListener('touchmove', f, false);
};


Function.prototype.method = function(name, f){
	if(!this.prototype[name]){
		this.prototype[name] = f;
		return this;
	}
}

Object.method('flick', function(range, f){
	if(typeof range == 'function'){
		var f = range,
		range = 50;
	}

	var startX, startY, curX, curY;
	
	this.touchEvent(function(e){
		e.preventDefault();
		var touch = e.touches[0];

		if(e.type == 'touchstart'){
			startX = curX = touch.pageX;
			startY = curY = touch.pageY;
		}
		if(e.type == 'touchmove'){
			curX = touch.pageX;
			curY = touch.pageY;
		}
		if(e.type == 'touchend'){
			var movedX = (startX - curX) * (-1),
			movedY = startY - curY;

			if(range < Math.abs(movedX)){
				return f(movedX, movedY);
			} else if(range < Math.abs(movedY)){
				return f(movedX, movedY);
			} else {
				return false;
			}
		}
	});
});