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.

<class="backToTopButton" href="#">&#8679; top</a>
.backToTopButton {
    
cursorpointer;
    
displaynone;
    
positionfixed;
    
bottom15px;
    
right15px;
    
padding4px;
    
backgroundrgb(848484);
    
color#bebebe;
    
border-radius5px;
    
opacity0.5;
    
transition300ms;
}
.
backToTopButton:hover {
    
opacity1;
}
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({top0behavior'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 1A6KbS5AmYQVAh5Zcy9rVSnMAoCEunLUqT

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