Last active
December 15, 2017 09:52
-
-
Save MrAntix/af5a269dd8d028e040debcbad6789097 to your computer and use it in GitHub Desktop.
smooth scroll to in angular
This file contains 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
import { Injectable, NgZone } from '@angular/core'; | |
@Injectable() | |
export class ScrollService { | |
constructor( | |
private ngZone: NgZone) { | |
} | |
scrollTo(selector: string, focus?: boolean): void { | |
const element = document.querySelector(selector) as HTMLElement; | |
if (!element) return; | |
const start = element.offsetParent.scrollTop; | |
const end = element.offsetTop - | |
(element.offsetParent.clientHeight - element.offsetHeight) / 2; | |
const stepsTotal = 25; | |
let steps = stepsTotal; | |
this.ngZone.runOutsideAngular(() => { | |
const move = () => { | |
requestAnimationFrame(() => { | |
element.offsetParent.scrollTop = start + | |
(end - start) * Math.cos(--steps / stepsTotal * Math.PI / 2); | |
if (steps) setTimeout(move, 10); | |
else if (focus) element.focus(); | |
}); | |
}; | |
move(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment