This chapter introduces how to implement a back-to-top effect for web pages using JS/CSS.

CSS Button Styles:

#myBtn { display: none; /*Hidden by default*/ position: fixed; bottom: 20px; right: 30px; z-index: 99; border: none; outline: none; background-color: red; /*Set the background color. You can set the color or image you want.*/ color: white; /*Text color*/ cursor: pointer; padding: 15px; border-radius: 10px; /*Rounded corners*/ } #myBtn:hover { background-color: #555; }

JS Code:

//The "Back to Top" button appears when the page scrolls down 20px. window.onscroll = function() {scrollFunction()}; function scrollFunction() {console.log(121); if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } //Click the button to return to the top. function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }

Try it »