Skip to content

Instantly share code, notes, and snippets.

@honsa
Created June 13, 2018 15:29
Show Gist options
  • Save honsa/35282fa386fe5624e3b0502496c9974a to your computer and use it in GitHub Desktop.
Save honsa/35282fa386fe5624e3b0502496c9974a to your computer and use it in GitHub Desktop.
Detect swipe events vanilla javascript
function swipeEvents(){
// patch CustomEvent to allow constructor creation (IE/Chrome) - resolved once initCustomEvent no longer exists
if ('initCustomEvent' in document.createEvent('CustomEvent')) {
window.CustomEvent = function (event, params) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
let evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
window.CustomEvent.prototype = window.Event.prototype;
}
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
document.addEventListener('touchend', handleTouchEnd, false);
let xDown = null;
let yDown = null;
let xDiff = null;
let yDiff = null;
let timeDown = null;
let startEl = null;
function handleTouchEnd(e) {
// if the user released on a different target, cancel!
if (startEl !== e.target) return;
let swipeThreshold = parseInt(startEl.getAttribute('data-swipe-threshold') || '20', 10); // default 10px
let swipeTimeout = parseInt(startEl.getAttribute('data-swipe-timeout') || '500', 10); // default 1000ms
let timeDiff = Date.now() - timeDown;
let eventType = '';
if (Math.abs(xDiff) > Math.abs(yDiff)) { // most significant
if (Math.abs(xDiff) > swipeThreshold && timeDiff < swipeTimeout) {
if (xDiff > 0) {
eventType = 'swiped-left';
}
else {
eventType = 'swiped-right';
}
}
}
else {
if (Math.abs(yDiff) > swipeThreshold && timeDiff < swipeTimeout) {
if (yDiff > 0) {
eventType = 'swiped-up';
}
else {
eventType = 'swiped-down';
}
}
}
if (eventType !== '') {
// fire event on the element that started the swipe
startEl.dispatchEvent(new CustomEvent(eventType, { bubbles: true, cancelable: true }));
if (console && console.log) console.log(eventType + ' fired on ' + startEl.tagName);
}
// reset values
xDown = null;
yDown = null;
timeDown = null;
}
function handleTouchStart(e) {
// if the element has data-swipe-ignore="true" we stop listening for swipe events
if (e.target.getAttribute('data-swipe-ignore') === 'true') return;
startEl = e.target;
timeDown = Date.now();
xDown = e.touches[0].clientX;
yDown = e.touches[0].clientY;
xDiff = 0;
yDiff = 0;
}
function handleTouchMove(e) {
if (!xDown || !yDown) return;
let xUp = e.touches[0].clientX;
let yUp = e.touches[0].clientY;
xDiff = xDown - xUp;
yDiff = yDown - yUp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment