Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Last active August 29, 2015 14:14
Show Gist options
  • Save restlessmedia/dea875032a335b2ec7ea to your computer and use it in GitHub Desktop.
Save restlessmedia/dea875032a335b2ec7ea to your computer and use it in GitHub Desktop.
Handing touch events
var tap = (function () {
var isSwipe = false;
var handlers = {};
var eventTypes = {
swipe: 'swipe',
tap: 'tap'
};
var applyEach = function (arr, context, args) {
var count = arr.length;
if (!count)
return;
var i = 0;
while (i < count) {
arr[i].apply(context, args);
i++;
}
};
var trigger = function (type, e) {
handlers[type][e.target] && applyEach(handlers[type][e.target], e.target, [e]);
if (e.currentTarget !== e.target)
handlers[type][e.currentTarget] && applyEach(handlers[type][e.currentTarget], e.currentTarget, [e]);
};
var on = function (element, type, handler) {
if (typeof(element) === 'string')
element = document.getElementById(element);
if (!handlers[type])
handlers[type] = [];
if (!handlers[type][element])
handlers[type][element] = [];
handlers[type][element].push(handler);
};
var addListener = function (type, handler) {
document.body.addEventListener(type, handler);
};
var init = function () {
addListener('touchstart', function () {
isSwipe = false;
});
addListener('touchend', function (e) {
if (isSwipe) {
trigger(eventTypes.swipe, e);
} else {
trigger(eventTypes.tap, e);
}
isSwipe = false;
});
addListener('touchmove', function (e) {
isSwipe = true;
});
addListener('touchcancel', function (e) {
isSwipe = false;
});
};
init();
return function (element) {
return{
on: function (type, handler) {
on(element, type, handler);
return this;
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment