]> BookStack Code Mirror - bookstack/blob - resources/js/components/back-to-top.js
Page Drafts: Added new "Delete Draft" action to draft menu
[bookstack] / resources / js / components / back-to-top.js
1 import {Component} from './component';
2
3 export class BackToTop extends Component {
4
5     setup() {
6         this.button = this.$el;
7         this.targetElem = document.getElementById('header');
8         this.showing = false;
9         this.breakPoint = 1200;
10
11         if (document.body.classList.contains('flexbox')) {
12             this.button.style.display = 'none';
13             return;
14         }
15
16         this.button.addEventListener('click', this.scrollToTop.bind(this));
17         window.addEventListener('scroll', this.onPageScroll.bind(this));
18     }
19
20     onPageScroll() {
21         const scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
22         if (!this.showing && scrollTopPos > this.breakPoint) {
23             this.button.style.display = 'block';
24             this.showing = true;
25             setTimeout(() => {
26                 this.button.style.opacity = 0.4;
27             }, 1);
28         } else if (this.showing && scrollTopPos < this.breakPoint) {
29             this.button.style.opacity = 0;
30             this.showing = false;
31             setTimeout(() => {
32                 this.button.style.display = 'none';
33             }, 500);
34         }
35     }
36
37     scrollToTop() {
38         const targetTop = this.targetElem.getBoundingClientRect().top;
39         const scrollElem = document.documentElement.scrollTop ? document.documentElement : document.body;
40         const duration = 300;
41         const start = Date.now();
42         const scrollStart = this.targetElem.getBoundingClientRect().top;
43
44         function setPos() {
45             const percentComplete = (1 - ((Date.now() - start) / duration));
46             const target = Math.abs(percentComplete * scrollStart);
47             if (percentComplete > 0) {
48                 scrollElem.scrollTop = target;
49                 requestAnimationFrame(setPos.bind(this));
50             } else {
51                 scrollElem.scrollTop = targetTop;
52             }
53         }
54
55         requestAnimationFrame(setPos.bind(this));
56     }
57
58 }