Skip to content

Instantly share code, notes, and snippets.

@v-dimitrov
Last active May 26, 2016 16:15
Show Gist options
  • Save v-dimitrov/d12093b8a93a7ed2a099c6a57da4d211 to your computer and use it in GitHub Desktop.
Save v-dimitrov/d12093b8a93a7ed2a099c6a57da4d211 to your computer and use it in GitHub Desktop.
create custom touch events for handsets
(function(doc) {
var createCustomEvent = function(e, n) {
var customEvent = doc.createEvent("CustomEvent");
customEvent.initCustomEvent(n, true, true, e.target);
e.target.dispatchEvent(customEvent);
customEvent = null;
return false
},
nm = true,
startPos = {
x: 0,
y: 0
},
endPost = {
x: 0,
y: 0
},
touch = {
touchstart: function(e) {
startPos = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
},
touchmove: function(e) {
nm = false;
endPost = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
},
touchend: function(e) {
if (!nm) {
var x = endPost.x - startPos.x,
xr = Math.abs(x),
y = endPost.y - startPos.y,
yr = Math.abs(y);
if (Math.max(xr, yr) > 20) {
createCustomEvent(e, (xr > yr ? (x < 0 ? 'swl' : 'swr') : (y < 0 ? 'swu' : 'swd')))
}
};
nm = true
},
touchcancel: function(e) {
nm = false
}
};
for (var event in touch) {
doc.addEventListener(event, touch[event], false);
}
})(document);
var swipeHandler = function(e) {
console.log(e.type, e)
};
document.body.addEventListener('swl', swipeHandler, false);
document.body.addEventListener('swr', swipeHandler, false);
document.body.addEventListener('swu', swipeHandler, false);
document.body.addEventListener('swd', swipeHandler, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment