So I've made a button in the right-bottom corner of my HTML-page, but I was wondering since it's the first time I've made this, if there is another better way to do this, or if you guys can see anything funky about the way I did this?
This post is mostly to learn how to do things the right way, since I'm a beginner at this.
Thanks for your help.
Here is my code --> if you want to GOTO: JSfiddle
var bottomPage = document.getElementById('bottomPage');
var topPage = document.getElementById('topPage');
var lastScrollTop = 0;
bottomPage.addEventListener('click', scrollBottom);
topPage.addEventListener('click', scrollTop);
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
window.addEventListener('scroll', function(){ // or element.addEventListener('scroll'....
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
bottomPage.style.display = 'none';
topPage.style.display = '';
} else {
bottomPage.style.display = '';
topPage.style.display = 'none';
}
lastScrollTop = st <= 0 ? 0 : st;
}, false);
function scrollBottom() {
window.scrollTo(0,document.body.scrollHeight);
bottomPage.style.display = 'none';
topPage.style.display = '';
}
function scrollTop() {
window.scrollTo(0, 0);
topPage.style.display = 'none';
bottomPage.style.display = '';
}
body{
height: 3000px;
background: white;
background: linear-gradient(to bottom, #33ccff 0%, #ff99cc 100%);
}
.right-corder-container {
position: fixed;
right: 20px;
bottom: 20px;
vertical-align: middle;
background: #dddddd79;
text-align: center;
width: 40px;
height: 40px;
border-radius: 100%;
display: inline-flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 25px;
color: white;
font-weight: bold;
text-decoration: none
}
.right-corder-container img {
width: 40px;
height: 40px;
}
.right-corder-container:hover {
background: #85858579;
cursor: pointer;
}
<body>
<button class='right-corder-container' id='bottomPage' type='button'><img src='https://i.postimg.cc/87f0hmm2/scroll-down.png'></button>
<button class='right-corder-container' style='display: none;' id='topPage' type='button'><img src='https://i.postimg.cc/Tp4sL4gj/scroll-up.png'></button>
</body>