CSS-scroll to top

Table of Contents

Step 1 Add HTML:

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

Step 2 Add CSS:

/* style_scroll_to_top */ #myBtn { display: none; position: fixed; bottom: 50px; right: 200px; z-index: 99; border: none; outline: none; background-color: red; color: white; /* cursor: pointer; */ padding: 15px; border-radius: 10px; } #myBtn:hover { background-color: #cc0000; } body { font-family: Verdana, Geneva, sans-serif; font-size: small; } /* end scroll to top Step 2 Add CSS style: */

Step 3 Add JavaScript:

//scroll to top Step 3 Add JavaScript: // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }

Example 1

Result View Example

Document

Document in project

You can Download PDF file.

Refference