yumechi-no-kuni/src/client/scripts/sticky-sidebar.ts

49 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-07-06 02:08:30 -05:00
export class StickySidebar {
private lastScrollTop = 0;
private container: HTMLElement;
2020-07-06 02:08:30 -05:00
private el: HTMLElement;
private spacer: HTMLElement;
private marginTop: number;
private isTop = false;
private isBottom = false;
private offsetTop: number;
2020-07-06 02:08:30 -05:00
constructor(container: StickySidebar['container'], marginTop = 0) {
this.container = container;
this.el = this.container.children[0] as HTMLElement;
this.el.style.position = 'sticky';
this.spacer = document.createElement('div');
this.container.prepend(this.spacer);
2020-07-06 02:08:30 -05:00
this.marginTop = marginTop;
this.offsetTop = this.container.getBoundingClientRect().top;
2020-07-06 02:08:30 -05:00
}
public calc(scrollTop: number) {
if (scrollTop > this.lastScrollTop) { // downscroll
const overflow = Math.max(0, (this.el.clientHeight + this.marginTop) - window.innerHeight);
2020-07-06 02:08:30 -05:00
this.el.style.bottom = null;
this.el.style.top = `${-overflow + this.marginTop}px`;
2020-07-06 02:08:30 -05:00
this.isBottom = (scrollTop + window.innerHeight) >= (this.el.offsetTop + this.el.clientHeight);
if (this.isTop) {
this.isTop = false;
this.spacer.style.marginTop = `${Math.max(0, this.lastScrollTop + this.marginTop - this.offsetTop)}px`;
2020-07-06 02:08:30 -05:00
}
} else { // upscroll
const overflow = (this.el.clientHeight + this.marginTop) - window.innerHeight;
2020-07-06 02:08:30 -05:00
this.el.style.top = null;
this.el.style.bottom = `${-overflow}px`;
2020-07-06 02:08:30 -05:00
this.isTop = scrollTop <= this.el.offsetTop;
if (this.isBottom) {
this.isBottom = false;
this.spacer.style.marginTop = `${this.lastScrollTop + this.marginTop - this.offsetTop - overflow}px`;
2020-07-06 02:08:30 -05:00
}
}
this.lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
}
}