For one of my apps I have written an auto-scrolling directive so that certain pages will scroll to anchor links when they are clicked rather than just immediately jumping to them (it also provides scroll-to-top functionality). It works great, except the motion is completely linear, there is no natural-feeling acceleration / deceleration. I would like to apply an easing function to the scroll movement so it feels more natural, but I am having trouble figuring out how to implement one. I think the solution would involve continuously re-calculating the increment as the page scrolls rather than just once at the beginning like I have it below, but so far my experiments with that have not been fruitful.
I'm sure someone else has already written a superior smooth-scrolling directive for Angular, but I'm interested in creating my own :-)
Anyone have any ideas?
@HostBinding('scrollTop') scrollPos: number; // initialized when scroll command is first received
private setIncrement(destPosition:number) : number {
let mod = (destPosition - this.scrollPos < 0) ? -1 : 1;
return mod*50;
}
private scrollTo(position:number) : void {
this.inc = this.setIncrement(position);
this.isScrolling = true;
this.moveIt(this.scrollPos + this.inc);
}
private moveIt(newPos:number) :void {
this.scrollPos = Math.min(newPos,this.bottomOfPage);
let diff = this.selectedAnchor.position - this.scrollPos;
let inView : boolean;
// ... code that determines if anchor is in view and sets inView ...
if ( inView || this.scrollPos >= (this.bottomOfPage)) {
// ... code that ends scrolling ...
}
else {
this.timer = global.setTimeout(()=>{
this.moveIt(this.scrollPos + this.inc);
},1);
}
}