Skip to content

Instantly share code, notes, and snippets.

@lukephills
Last active August 29, 2015 14:08
Show Gist options
  • Save lukephills/33ae64b8c16975bfe27e to your computer and use it in GitHub Desktop.
Save lukephills/33ae64b8c16975bfe27e to your computer and use it in GitHub Desktop.
Touch, move & swipe directions
var Event = (function(){
/* Config vars */
var MIN_SWIPE = 30,
startPos = [],
endPos = [];
var _listenEvents = function(element, callback){
element.addEventListener('touchstart', function(e){
_onTouchStart(e);
});
element.addEventListener('touchmove', function(){
_onTouchMove(callback);
});
element.addEventListener('touchend', function(e){
_onTouchEnd(e, callback);
});
};
var _onTouchStart = function(e){
var touch = e.changedTouches[0]; // reference first touch point (ie: first finger)
startPos.push(parseInt(touch.clientX), parseInt(touch.clientY));
e.preventDefault();
};
var _onTouchMove = function(){
//TODO
};
var _onTouchEnd = function(e, callback){
var touch = e.changedTouches[0]; // reference first touch point (ie: first finger)
var direction;
endPos.push(parseInt(touch.clientX), parseInt(touch.clientY));
if (startPos[0] < endPos[0] && (endPos[0] - startPos[0] > MIN_SWIPE)){
direction = 'LEFT';
} else if (startPos[0] > endPos[0] && (startPos[0] - endPos[0] > MIN_SWIPE)){
direction = 'RIGHT';
} else if (startPos[1] > endPos[1] && (startPos[1] - endPos[1] > MIN_SWIPE)){
direction = 'UP';
} else if (startPos[1] < endPos[1] && (endPos[1] - startPos[1] > MIN_SWIPE)){
direction = 'DOWN';
}
callback(direction, endPos);
//Check event type
_onTouchCancel();
};
var _onTouchCancel = function(){
startPos = [];
endPos = [];
};
var swipe = function(element, callback){
_listenEvents(element, callback);
};
return {
swipe: swipe
};
})();
var app = (function(event){
var swipeArea = document.getElementById('swipeArea');
var arrowWidth = 60;
var containerWidth = 320;
var init = function(){
event.swipe(swipeArea, function(direction, endPos){
console.log(direction);
});
};
return {
init : init
};
})(Event);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment