summaryrefslogtreecommitdiff
path: root/source/helpers/preserve-scroll.ts
blob: 9e5bbda3e1c7c5fca879755153eee84d5b12a9ae (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);
		});
	};
}