code everywhere

adding a smooth scroll to top button to your webpage

posted on February 10, 2019, 12:00 am in js, css

Make navigation easier with a smooth scrolling go to top button using some simple Javascript and CSS.

<a class="backToTopButton" href="#">&#8679; 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="#">&#8679; top</div>

would also work.

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy