summaryrefslogtreecommitdiff
path: root/source/libs/anchor-scroll.ts
blob: 559864da4be6bcd865828eca118b9a05e6396fb9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export default async function anchorScroll(
	action: VoidFunction | AsyncVoidFunction,
	anchor: Element = document.elementFromPoint(innerWidth / 2, innerHeight / 2)!
): Promise<void> {
	if (anchor) {
		const originalPosition = anchor.getBoundingClientRect().top;

		await action();

		requestAnimationFrame(() => {
			const newPositon = anchor.getBoundingClientRect().top;
			window.scrollBy(0, newPositon - originalPosition);
		});
	} else {
		// Anchor not found; proceed without anchoring
		action();
	}
}