1
Fork 0
tildes-reextended/source/content-scripts/features/back-to-top.tsx

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-06-23 10:52:03 +00:00
import debounce from "debounce";
import {Component} from "preact";
import {log} from "../../utilities/exports.js";
type Props = Record<string, unknown>;
type State = {
hidden: boolean;
};
export class BackToTopFeature extends Component<Props, State> {
constructor() {
super();
this.state = {
hidden: true,
};
// Add a "debounced" handler to the scroll listener, this will make it so
// the handler will only run after scrolling has ended for 150ms.
2023-06-23 10:52:03 +00:00
window.addEventListener("scroll", debounce(this.scrollHandler, 150));
// Run the handler once in case the page was already scroll down.
this.scrollHandler();
log(`Back To Top: Initialized.`);
}
scrollHandler = () => {
this.setState({hidden: window.scrollY < 500});
};
scrollToTop = () => {
2023-06-23 10:52:03 +00:00
window.scrollTo({behavior: "smooth", top: 0});
};
render() {
2023-06-23 10:52:03 +00:00
const hidden = this.state.hidden ? "trx-hidden" : "";
2023-06-23 10:52:03 +00:00
return (
<a
id="trx-back-to-top"
2023-06-23 10:52:03 +00:00
class={`btn btn-primary ${hidden}`}
onClick={this.scrollToTop}
>
Back To Top
</a>
2023-06-23 10:52:03 +00:00
);
}
}