Created
April 15, 2012 19:40
-
-
Save NekR/2394465 to your computer and use it in GitHub Desktop.
Small swipe API provides use swipes like plain events.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const | |
SWIPE_OFFSET = 50, | |
SWIPE_ANIMATION = 400, | |
SWIPE_HORIZONTAL = 1, | |
SWIPE_VERTICAL = 2, | |
SWIPE_BOTH = 3, | |
TAP_DELAY = 100, | |
LONG_TAP_DELAY = 500; | |
document.addEventListener('mousedown', function(e){ | |
var upListener = function(e){ | |
if(swipeMap){ | |
swipeMap = 0; | |
let swipe = new MouseEvent('swipeend', e); | |
e.target.dispatchEvent(swipe); | |
}else if(!tapDispatched){ | |
tapTimer && window.clearTimeout(tapTimer); | |
longTapTimer && window.clearTimeout(longTapTimer); | |
waitTap(); | |
let (tapend = new MouseEvent('tapend', e)){ | |
e.target.dispatchEvent(tapend); | |
} | |
} | |
document.removeEventListener('mouseup', upListener); | |
document.removeEventListener('mousemove', moveListener); | |
}, | |
moveListener = function(e){ | |
if(!(swipeMap & SWIPE_HORIZONTAL) && Math.abs(startX - e.clientX) > SWIPE_OFFSET){ | |
swipeMap |= SWIPE_HORIZONTAL; | |
Object.defineProperty(e, 'detail', { | |
value: SWIPE_HORIZONTAL, | |
configurable: true | |
}); | |
let swipe = new MouseEvent('swipestart', e); | |
e.target.dispatchEvent(swipe); | |
} | |
if(!(swipeMap & SWIPE_VERTICAL) && Math.abs(startY - e.clientY) > SWIPE_OFFSET){ | |
swipeMap |= SWIPE_VERTICAL; | |
Object.defineProperty(e, 'detail', { | |
value: SWIPE_VERTICAL, | |
configurable: true | |
}); | |
let swipe = new MouseEvent('swipestart', e); | |
e.target.dispatchEvent(swipe); | |
} | |
latestEvent = e; | |
}, | |
startX = e.clientX, | |
startY = e.clientY, | |
// 1 - horizontal | |
// 2 - vertical | |
// 3 - both | |
swipeMap = 0, | |
tapTimer = 0, | |
longTapTimer = 0, | |
latestEvent, | |
tapDispatched, | |
waitTap = function(){ | |
if(swipeMap) return; | |
var tap = new MouseEvent('tapstart', latestEvent || e); | |
e.target.dispatchEvent(tap); | |
tapTimer = null; | |
tapDispatched = true; | |
}; | |
document.addEventListener('mouseup', upListener); | |
document.addEventListener('mousemove', moveListener); | |
tapTimer = window.setTimeout(waitTap, TAP_DELAY); | |
longTapTimer = window.setTimeout(function(){ | |
if(swipeMap || tapTimer) return; | |
var tap = new MouseEvent('longtapstart', latestEvent || e); | |
e.target.dispatchEvent(tap); | |
longTapTimer = null; | |
}, LONG_TAP_DELAY); | |
//e.stopImmediatePropagation(); | |
//e.preventDefault(); | |
}, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment