Last active
December 8, 2016 07:14
-
-
Save kevinports/10342978 to your computer and use it in GitHub Desktop.
Custom scroll implementation for touch
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
// Handle touch events | |
var $win = $(window), | |
scroller = new Scroller(); | |
this.$win.on("touchstart", function(e){ | |
e.preventDefault(); | |
scroller.onTouchStart(e.originalEvent); | |
}); | |
this.$win.on("touchmove", function(e){ | |
e.preventDefault(); | |
scroller.onTouchMove(e.originalEvent); | |
}); | |
this.$win.on("touchend", function(e){ | |
e.preventDefault(); | |
scroller.onTouchEnd(e.originalEvent); | |
}); | |
// Scroller class | |
function Scroller() { | |
this.startTouchY = 0; | |
this.currentY = 0; | |
} | |
Scroller.prototype = { | |
onTouchStart: function(e) { | |
this.currentY = this.startTouchY = e.touches[0].clientY; | |
this.startTime = e.timeStamp; | |
this.contentStartOffsetY = e.touches[0].pageY - this.startTouchY; | |
}, | |
onTouchMove: function(e) { | |
this.currentY = e.touches[0].clientY; | |
this.deltaY = this.currentY - this.startTouchY; | |
this.deltaTime = e.timeStamp; | |
this.newY = (-this.deltaY) + this.contentStartOffsetY; | |
this.animateTo(this.newY); | |
}, | |
onTouchEnd: function(e) { | |
distance = Math.abs(this.currentY - this.startTouchY); | |
if(distance > 20){ | |
this.doMomentum(); | |
} | |
}, | |
animateTo: function(offsetY) { | |
this.contentOffsetY = offsetY; | |
this.tween = TweenLite.to(window, 0.01, {scrollTo:{y:offsetY}, ease:Power2.easeOut}); | |
}, | |
getEndVelocity: function(){ | |
var distance = (this.currentY - this.startTouchY) * -1, | |
time = this.deltaTime -this.startTime, | |
velo = distance/time, | |
dir = velo < 0 ? -1 : 1, | |
abs = Math.abs(velo), | |
velocity = _.map(abs, 0, 2.5, 0.25, 1); | |
velocity *= dir; | |
return velocity; | |
}, | |
doMomentum: function() { | |
var velocity = this.getEndVelocity(), | |
acceleration = velocity < 0 ? 0.0005 : -0.0005, | |
displacement = - (velocity * velocity) / (2 * acceleration), | |
time = (- velocity / acceleration) * 0.001, | |
newY = this.contentOffsetY + displacement; | |
this.contentOffsetY = newY; | |
this.tween = TweenMax.to(window, time, { | |
scrollTo : { y : newY, autoKill:true }, | |
ease: Expo.easeOut, | |
overwrite: 5 | |
}); | |
} | |
} | |
// Map function from "_" utility namespace | |
_ = { | |
map: function(value, istart, istop, ostart, ostop) { | |
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment