In this tutorial, We’ll learn about how to scroll to the top using js.
We’ll understand it by one example,
First we add four section in a html document and add button for a ScrollToTop and we use top icon button.
<i class=”fa fa-arrow-up” aria-hidden=”true”></i>
demo.html
<button class="backtotop" id="backtotop" onclick="topFunction()"><i class="fa fa-arrow-up" aria-hidden="true"></i></button> <section class="top-classs"> <h1>first page home</h1> </section> <section class="second-classs"> <h1>second page home</h1> </section> <section class="third-classs"> <h1>third page home</h1> </section> <section class="four-classs"> <h1>forth page home</h1> </section>
style.css :
Here is some style for section and button
html { scroll-behavior: smooth; }
the above css use to scroll page smoothly.
* { margin: 0; padding: 0; } html { scroll-behavior: smooth; } .top-classs, .second-classs, .third-classs, .four-classs { background-color: silver; height: 100vh; } .second-classs { background-color: gray; } .third-classs { background-color: darkgray; } .four-classs { background-color: black; } .backtotop { background-color: white; height: 50px; width: 50px; padding: 20px; border-radius: 50%; border: 1px solid red; z-index: 999; position: fixed; bottom: 30px; right: 30px; display: none; } .backtotop i { color: black; font-size: 20px; position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%); } h1 { color: white; text-align: center; padding-top: 150px; text-transform: capitalize; }
custom.js :
Now in the JavaScript file :
first, we select a link button.
var backtotop= document.getElementById(“backtotop”)
then define a function to scroll page to top,
When the we scroll the page after scroll Top 350 then the button will display .If page is below 350 then scroll button not display
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350)
Now when we click on this button it scroll to top and button will be not display.
<script> var backtTotop = document.getElementById("backtotop") window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) { backtTotop.style.display = "block"; } else { backtTotop.style.display = "none"; } } function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } </script>