UNPKG

scrl

Version:

Page acceleration based scroll animation.

3 lines (2 loc) 2.18 kB
function t(){return t=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var o=arguments[i];for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(t[s]=o[s])}return t},t.apply(this,arguments)}class i{constructor(i){this._raf=null,this._positionY=0,this._velocityY=0,this._targetPositionY=0,this._targetPositionYWithOffset=0,this._direction=0,this.scrollTo=t=>{if(t&&t.nodeType)this._targetPositionY=Math.round(t.getBoundingClientRect().top+window.pageYOffset);else{if(parseInt(this._targetPositionY)!==this._targetPositionY)return void console.error("Argument must be a number or an element.");this._targetPositionY=Math.round(t)}this._targetPositionY>document.documentElement.scrollHeight-window.innerHeight&&(this._targetPositionY=document.documentElement.scrollHeight-window.innerHeight),this._positionY=document.body.scrollTop||document.documentElement.scrollTop,this._direction=this._positionY>this._targetPositionY?-1:1,this._targetPositionYWithOffset=this._targetPositionY+this._direction,this._velocityY=0,this._positionY!==this._targetPositionY?(this.options.onStart(),this._animate()):this.options.onAlreadyAtPositions()},this._animate=()=>{this._update(),this._render(),1===this._direction&&this._targetPositionY>this._positionY||-1===this._direction&&this._targetPositionY<this._positionY?(this._raf=requestAnimationFrame(this._animate),this.options.onTick()):(this._positionY=this._targetPositionY,this._render(),this._raf=null,this.options.onTick(),this.options.onEnd())},this._update=()=>{const t=this._targetPositionYWithOffset-this._positionY;return this._velocityY+=t*this.options.acceleration,this._velocityY*=this.options.friction,this._positionY+=this._velocityY,Math.abs(t)},this._render=()=>{window.scrollTo(0,this._positionY)},this.options=t({},{onAlreadyAtPositions:()=>{},onCancel:()=>{},onEnd:()=>{},onStart:()=>{},onTick:()=>{},friction:.7,acceleration:.04},i),i&&i.friction&&(this.options.friction=1-i.friction),window.addEventListener("mousewheel",t=>{this._raf&&(this.options.onCancel(),cancelAnimationFrame(this._raf),this._raf=null)},{passive:!0})}}export{i as default}; //# sourceMappingURL=index.modern.js.map