HTML
xxxxxxxxxx
1
<!-- Back to top button -->
2
<button
3
type="button"
4
class="btn btn-danger btn-floating btn-lg"
5
id="btn-back-to-top"
6
>
7
<i class="fas fa-arrow-up"></i>
8
</button>
9
10
<!-- Explanation -->
11
<div class="container mt-4 text-center" style="height: 2000px">
12
<p>
13
Start scrolling the page and a red
14
<strong>"Back to top" button </strong> will appear in the
15
<strong>bottom right corner</strong> of the screen.
16
</p>
17
18
<p>Click this button and you will be taken to the top of the page.</p>
19
</div>
CSS
xxxxxxxxxx
1
#btn-back-to-top {
2
position: fixed;
3
bottom: 20px;
4
right: 20px;
5
display: none;
6
}
JS
xxxxxxxxxx
1
//Get the button
2
let mybutton = document.getElementById("btn-back-to-top");
3
4
// When the user scrolls down 20px from the top of the document, show the button
5
window.onscroll = function () {
6
scrollFunction();
7
};
8
9
function scrollFunction() {
10
if (
11
document.body.scrollTop > 20 ||
12
document.documentElement.scrollTop > 20
13
) {
14
mybutton.style.display = "block";
15
} else {
16
mybutton.style.display = "none";
17
}
18
}
19
// When the user clicks on the button, scroll to the top of the document
20
mybutton.addEventListener("click", backToTop);
21
22
function backToTop() {
23
document.body.scrollTop = 0;
24
document.documentElement.scrollTop = 0;
25
}
Console errors: 0