Last active
January 18, 2016 03:17
-
-
Save kotarok/36eeb16115f79268fdc3 to your computer and use it in GitHub Desktop.
JavaScript watchSwipe() event observer.
This file contains hidden or 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
var watchSwipe = function(el) { | |
var d = {}; | |
var SWIPWE = 'swipe', | |
FLICK = 'flick', | |
DIRECTIONS = ['Up', 'Left', 'Right', 'Down'], | |
SWIPE_MIN_MOVE = 50, | |
FLICK_MIN_MOVE = 30, | |
FLICK_MIN_VELO = 1; | |
el.touchstartListener_ = function(e) { | |
d.duration = Date.now(); | |
d.distance = 0; | |
d.startX = e.touches[0].pageX; | |
d.startY = e.touches[0].pageY; | |
}; | |
el.touchendListener_ = function(e) { | |
// set end coordination if it moves further than minimum length | |
d.endX = e.changedTouches[0].pageX; | |
d.endY = e.changedTouches[0].pageY; | |
var moveX = Math.abs(d.endX - d.startX); | |
var moveY = Math.abs(d.endY - d.startY); | |
d.distance = Math.sqrt(moveX * moveX + moveY * moveY); | |
if (Math.abs(d.distance) < SWIPE_MIN_MOVE) { | |
return false; | |
} | |
// Calc velocity | |
d.duration = Date.now() - d.duration; | |
d.velocity = d.distance / d.duration; | |
// detect move direction from relative coordination | |
var direction = DIRECTIONS[parseInt( | |
((moveY > -moveX) - 0 + '') + | |
((moveY > moveX) - 0), | |
2)]; | |
var verboseSwipeEventName = SWIPWE + direction; | |
var verboseFlickEventName = FLICK + direction; | |
d.direction = direction.toLowerCase(); | |
if (d.velocity > FLICK_MIN_VELO) { | |
d.type = FLICK; | |
el.dispatchEvent(new CustomEvent(FLICK, {detail: d})); | |
el.dispatchEvent(new CustomEvent(verboseFlickEventName, {detail: d})); | |
} else { | |
d.type = SWIPWE; | |
} | |
el.dispatchEvent(new CustomEvent(SWIPWE, {detail: d})); | |
el.dispatchEvent(new CustomEvent(verboseSwipeEventName, {detail: d})); | |
}; | |
el.addEventListener('touchstart', el.touchstartListener_); | |
el.addEventListener('touchend', el.touchendListener_); | |
}; | |
var unwatchSwipe = function() { | |
el.removeEventListener('touchstart', el.touchstartListner_); | |
el.removeEventListener('touchend', el.touchendListener_); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can watch
swipe
orflick
event easily via general.addEventListener
API.Watch swipe or flick motion on given element. If it's detected, fire custom event, like:
Those events are fired by velocity and direction of touch movement. If it moves fast enough,
flick
event would be fired as well asswipe
event.event
object hasdetail
property which has more detail information, like: coordinations, direction, distance, duration or velocity. You can use them if needed.Also you can do
unwatchSwipe(el)
.