Skip to content

Instantly share code, notes, and snippets.

@rhyzx
Last active October 11, 2015 01:58
Show Gist options
  • Save rhyzx/3785554 to your computer and use it in GitHub Desktop.
Save rhyzx/3785554 to your computer and use it in GitHub Desktop.
slider for mobile browser
/*
<div id="slider">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
*/
!(function CSS3Slider() {
var slider = document.querySelector('#slider')
, style = slider.style,
, width = slider.firstElementChild.offsetWidth
style.display = '-webkit-box'
style.webkitTransition = '-webkit-transform .5s ease-in-out'
//style.webkitTransform = 'translate3d(0, 0, 0)'
style.webkitTransformStyle = 'preserve-3d'
style.webkitTransform = 'translateX(0)'
slider.addEventListener('touchstart', start, false)
slider.addEventListener('touchmove', move, false)
document.addEventListener('touchend', end, false)
var left=0, sx, sy, x, y, state // state 0:init, 1:moving, 2:canceled
function start(evt) {
sx = evt.touches[0].pageX
sy = evt.touches[0].pageY
state = 0
}
function move(evt) {
x = evt.touches[0].pageX
y = evt.touches[0].pageY
if(state === 1) {
style.webkitTransform = 'translateX(' +(left +x -sx) +'px)'
} else if(state === 0) {
if(Math.abs(sx -x) > 20) { // slide horizontal: start moving
evt.preventDefault()
style.webkitTransitionDuration = 0
state = 1
} else if(Math.abs(sy -y) > 20) { // slide vertical: canceled
state = 2
}
}
}
function end(evt) {
if(state === 1) {
if(x - sx > 50) {
left += width
} else if(x- sx < -50) {
left -= width
}
style.webkitTransitionDuration = ''
style.webkitTransform = 'translateX(' +left +'px)'
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment