I need to show/hide two floating buttons on page scrolling for back to top and back to bottom.
Here is my code.
It should shows, back to top button while scrolling page to bottom (it works) and shows back to bottom button while scrolling page to top.(not working properly)
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
document.getElementById("toTop").style.display = "inline";
document.getElementById("toBottom").style.display = "none";
} else {
document.getElementById("toTop").style.display = "none";
document.getElementById("toBottom").style.display = "inline";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// When the user clicks on the button, scroll to the bottom of the document
function botFunction() {
let height = document.body.clientHeight;
document.body.scrollTop = height;
document.documentElement.scrollTop = height;
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 20px;
}
#toTop {
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;
}
#toTop:hover {
background-color : #555;
}
#toBottom {
display : none;
position : fixed;
top : 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;
}
#toBottom:hover {
background-color : #555;
}
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
0<br><br> 1<br><br> 2<br><br> 3<br><br> 4<br><br> 5<br><br> 6<br><br> 7<br><br> 8<br><br> 9<br><br>
<button onclick="topFunction()" id="toTop" title="Go to top">↑</button>
<button onclick="botFunction()" id="toBottom" title="Go to top">↓</button>
2
Answers
For that purpose, I would include detection of the scroll direction.
By using it, your code could look like this:
I will do that this way…