Created
November 14, 2012 11:25
-
-
Save timwhitlock/4071631 to your computer and use it in GitHub Desktop.
Swiper code snippet from http://jsfiddle.net/timwhitlock/2vJDs/
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
/** | |
* swipe inertia demo for browsers supporting the touchstart family of events | |
* @param HTMLElement | |
* @param Function touchend callback with speed and direction of swipe | |
*/ | |
function initSwiper( el, callback ){ | |
var xstart = 0, // <- initial scroll position on first touch | |
tstarts = [], // <- time each touch started | |
xoffset = [], // <- initial x position of each touch | |
yoffset = []; // <- initial y position of each touch | |
/** | |
* Utility for getting current time in milliseconds | |
*/ | |
var now = Date.now || function(){ | |
return new Date().getTime(); | |
}; | |
/** | |
* Initialize swipe on touchstart | |
*/ | |
function onTouchStart( event ){ | |
var t = now(); | |
eachTouchEvent( event, function( i, e ){ | |
tstarts[i] = t; | |
xoffset[i] = e.clientX; | |
} ); | |
xstart = el.scrollLeft; | |
return true; | |
} | |
/** | |
* Callback for touchmove | |
*/ | |
function onTouchMove( event ){ | |
var xmove, ymove; | |
eachTouchEvent( event, function( i, e ){ | |
xmove = xoffset[i] - e.clientX; | |
ymove = yoffset[i] - e.clientY; | |
} ); | |
if( ymove && Math.abs(ymove) > Math.abs(xmove) ){ | |
// this was intended as a vertical scroll - probably of the page | |
// we will allow this event through so the OS/browser can handle it. | |
return true; | |
} | |
if( xmove ){ | |
// else take control of horizonal scroll and cancel event | |
el.scrollLeft = Math.max( 0, xstart + xmove ); | |
} | |
event.preventDefault(); | |
return false; | |
} | |
/** | |
* Callback when touch released | |
*/ | |
function onTouchEnd( event ){ | |
eachTouchEvent( event, function( i, e ){ | |
var touchtime = now() - tstarts[i], | |
touchmoved = xoffset[i] - e.clientX, | |
speed = Math.abs( touchmoved ) / touchtime, | |
direction = touchmoved ? ( touchmoved < 0 ? -1 : 1 ) : 0; | |
callback( speed, direction ); | |
} ); | |
return true; | |
} | |
/** | |
* multi-touch iterator | |
*/ | |
function eachTouchEvent( event, callback ){ | |
var i = -1, | |
touched = event.originalEvent || event, | |
changed = touched.changedTouches||[]; | |
while( ++i < changed.length ){ | |
callback( i, changed[i] ); | |
} | |
} | |
// bind standard touch events | |
el.addEventListener('touchstart', onTouchStart, false ); | |
el.addEventListener('touchmove', onTouchMove, false ); | |
el.addEventListener('touchend', onTouchEnd, false ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment