summaryrefslogtreecommitdiff
path: root/source/helpers/preserve-scroll.ts
blob: 30074cd05822116bf08953fd1f70f18b87cd7a0c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default function preserveScroll(
	anchor: Element = document.elementFromPoint(innerWidth / 2, innerHeight / 2)!
): VoidFunction {
	const originalPosition = anchor.getBoundingClientRect().top;

	/**
	Resets the previously-saved scroll
	*/
	return () => {
		requestAnimationFrame(() => {
			const newPosition = anchor.getBoundingClientRect().top;
			window.scrollBy(0, newPosition - originalPosition);
		});
	};
}