adding a smooth scroll to top button to your webpage
posted on February 10, 2019, 12:00 am in
Make navigation easier with a smooth scrolling go to top button using some simple Javascript and CSS.
<a class="backToTopButton" href="#">⇧ top</a>
.backToTopButton {
cursor: pointer;
display: none;
position: fixed;
bottom: 15px;
right: 15px;
padding: 4px;
background: rgb(84, 84, 84);
color: #bebebe;
border-radius: 5px;
opacity: 0.5;
transition: 300ms;
}
.backToTopButton:hover {
opacity: 1;
}
var btn = document.querySelector('.backToTopButton');
window.addEventListener('scroll', function(){
if(this.pageYOffset >= 250)
btn.style.display = 'block';
else
btn.style.display = 'none';
});
btn.addEventListener('click', function(e) {
window.scrollTo({top: 0, behavior: 'smooth'});
}, false);
⇧ top
Demo
View the bottom right of this page.
No-JS option
If you don't need the smooth animation, or don't mind if the button is always visible, a simple:
<div class="backToTopButton" href="#">⇧ top</div>
would also work.