Skip to content

Instantly share code, notes, and snippets.

@yoshihitofujiwara
Last active July 5, 2016 02:51
Show Gist options
  • Save yoshihitofujiwara/3462871 to your computer and use it in GitHub Desktop.
Save yoshihitofujiwara/3462871 to your computer and use it in GitHub Desktop.
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;
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment