Last active
August 29, 2015 14:04
-
-
Save LeiZeng/92d70fb0da597789ab08 to your computer and use it in GitHub Desktop.
Simple and cross platform horizontal swipe event handler
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
;(function($, undefined) { | |
"use strict" | |
var isTouch = 'ontouchstart' in window; | |
function bindSwipeEvent(o) { | |
var $win = $(window), | |
$el = o.el, | |
startX = 0, | |
touchX, | |
distX = 0, | |
touching, | |
swiping; | |
var startEvent = isTouch ? 'touchstart' : 'mousedown', | |
moveEvent = isTouch ? 'touchmove' : 'mousemove', | |
endEvent = isTouch ? 'touchleave touchend touchcancel' : 'mouseup mouseleave' | |
$el | |
.on(startEvent, startTouch) | |
.on(moveEvent, handleTouch) | |
.on(endEvent, endTouch) | |
function startTouch (e) { | |
touching = true; | |
swiping = null; | |
if (isTouch) { | |
startX = e.originalEvent.touches[0].clientX; | |
} else { | |
startX = e.clientX; | |
} | |
if(o.start) o.start(e) | |
} | |
function handleTouch (event) { | |
if(!isTouch && !touching) return true | |
var touchList | |
if (isTouch) { | |
touchX = event.originalEvent.touches[0].clientX; | |
} else { | |
touchX = parseInt(event.clientX, 10); | |
} | |
distX = touchX - startX; | |
// once start swiping, block the touch scroll | |
if (swiping) { | |
if(o.move) o.move(event, distX) | |
event.preventDefault(); | |
} else { | |
if(distX > 4 || distX < -4) { | |
swiping = true; | |
if(o.move) o.move(event, distX) | |
event.preventDefault(); | |
} | |
} | |
} | |
function endTouch (e) { | |
touching = null; | |
swiping = null; | |
if(o.end) o.end(e, distX); | |
startX = distX = 0; | |
} | |
} | |
bindSwipeEvent({ | |
el: $('.swiping-element'), | |
start: function(e) { | |
// do something when swiping start | |
}, | |
move: function(e, distX) { | |
// do something when swiping | |
}, | |
end: function(e, distX) { | |
// do something after swiping | |
} | |
}); | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment