Skip to content

Instantly share code, notes, and snippets.

@hongkheng
Last active August 29, 2015 14:23
Show Gist options
  • Save hongkheng/9524f7b63c03deafa4fa to your computer and use it in GitHub Desktop.
Save hongkheng/9524f7b63c03deafa4fa to your computer and use it in GitHub Desktop.
Moving average
//Moving average
// v(t) = a * V(t) + (1-a)*v(t-1)
// http://scrollerjs.com/talks/velocity2014/#1
function moveStep () { // triggered every 17ms~
var v = (currentPos - prevPos) / (currentTime - prevTime); // current velocity
self.velocity = 0.6 * v + 0.4 * self.velocity; // Applying moving average formmula
self.translate(self.x, self.y); // debounce move event from animation
requestAnimationFrame(moveStep);
}
// http://ariya.ofilabs.com/2013/11/javascript-kinetic-scrolling-part-2.html
// scroll to a given position in a give time (momentum)
scrollTo: function (pos, duration, curve) {
var startTime = NOW(),
deltaPos = startPos - pos,
destTime = startTime + duration;
function step () {
var now = NOW();
if (now >= destTime) {
return; // Animation is done!
}
percentageTime = (now - startTime) / duration;
percentageProgress = curve(percentageTime);
// Calculate new position based on the result of the function
newPos = deltaPos * percentageProgress + startPos;
requestAnimationFrame(step);
}
step();
}
// scroller
attachItemInSurface: function (item, surface, config) {
var offset = config.offset;
// Recalculate styles (DOM write)
surface.dom.appendChild(item.dom);
// This will force a paint (DOM read)
height = surface.dom.offsetHeight;
offsetY = offset - height;
surface.dom.style[transform] =
'translate3d(0, ' + offsetY + ', 0)';
}
//plugins
var myPlugin = {
init: function () {
this.on('_update', this._updateMyPlugin); // Register a listener on update
this.on('_refresh', this._refreshMyPlugin); // Register a listener on refresh
},
_getVelocity: function () { // Overrides the original scroller function
return 2;
},
_refreshMyPlugin: function () { // Adds some internal state
this.state = 'refreshed';
},
_updateMyPlugin: function () { // Do something external to the scroller
var str = this.opts.myPlugin;
console.log(str + this.y);
}
};
//Attach plugins to the scroller
var scroller = new Scroller('#wrapper', {myPlugin: 'YAY!: '});
scroller.plug(myPlugin);
//Add and initialize plugins on bootstrap
var scroller2 = new Scroller('#wrapper', {
plugins: ['MyPlugin2'] // If is already registered under Scroller.plugins
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment