summaryrefslogtreecommitdiff
path: root/src/client/scripts/scroll.ts
blob: a915f2e9ef8f64eb13bd9123b5cc75eb65965f56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export function getScrollContainer(el: Element | null): Element | null {
	if (el == null || el.tagName === 'BODY') return null;
	const overflow = window.getComputedStyle(el).getPropertyValue('overflow');
	if (overflow.endsWith('auto')) { // xとyを個別に指定している場合、hidden auto みたいな値になる
		return el;
	} else {
		return getScrollContainer(el.parentElement);
	}
}

export function getScrollPosition(el: Element | null): number {
	const container = getScrollContainer(el);
	return container == null ? window.scrollY : container.scrollTop;
}

export function onScrollTop(el: Element, cb) {
	const container = getScrollContainer(el) || window;
	const onScroll = ev => {
		if (!document.body.contains(el)) return;
		const pos = getScrollPosition(el);
		if (pos === 0) {
			cb();
			container.removeEventListener('scroll', onscroll);
		}
	};
	container.addEventListener('scroll', onScroll, { passive: true });
}

export function scroll(el: Element, top: number) {
	const container = getScrollContainer(el);
	if (container == null) {
		window.scroll({ top: top, behavior: 'instant' });
	} else {
		container.scrollTop = top;
	}
}