-
Notifications
You must be signed in to change notification settings - Fork 0
/
topbutton.js
73 lines (67 loc) · 1.77 KB
/
topbutton.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(function() {
const template = document.createElement('template');
template.innerHTML = `
<style>
#topbutton {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#topbutton:hover {
background-color: #555;
}
</style>
<button id="topbutton" title="Go to top">Top</button>
`;
class TopButton extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({
mode: 'open'
});
this._shadowRoot.appendChild(template.content.cloneNode(true));
var topbutton = this._shadowRoot.getElementById('topbutton');
// When the user clicks on the button, scroll to the top of the document
this.addEventListener('click', () => {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
var scrolling = false;
window.onscroll = () => {
scrolling = true;
};
setInterval(() => {
if (scrolling) {
scrolling = false;
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topbutton.style.display = 'block';
} else {
topbutton.style.display = 'none';
}
}
}, 250);
// or for modern browsers
document.addEventListener('wheel', () => {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topbutton.style.display = 'block';
} else {
topbutton.style.display = 'none';
}
}, {
capture: false,
passive: true
});
}
}
window.customElements.define('top-button', TopButton);
})();