Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Last active December 15, 2017 09:52
Show Gist options
  • Save MrAntix/af5a269dd8d028e040debcbad6789097 to your computer and use it in GitHub Desktop.
Save MrAntix/af5a269dd8d028e040debcbad6789097 to your computer and use it in GitHub Desktop.
smooth scroll to in angular
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