Scroll to top button feature in a website allow users to scroll to top of web page smoothly.
If website page have more content then it is tough task for user to go top of such web page after reading its content. So for good user experience we must add scroll to top button so that user can easily go to top of page.
In this tutorial, we are going to discuss How To Create Scroll To Top Button With jQuery .
Scroll back to top button feature gives good experience to your website visitors to navigate to top of webpage when it have lots of content to scroll back.
We check if scrollbar positions from the top of page and if it is greater than certain value then we fadein a scroll to top button so that user can easily navigate to top of page.
Also read:
Display Loading Image While Page Loads Using jQuery and CSS
Dynamic Content Load Using jQuery and AJAX in PHP
Dynamic Dependent Select Box Using jQuery,Ajax and PHP
Scroll To Top In jQuery
HTML Code:
This is an HTML code in body to display back to top button.
<p id="go-to-top"> <a href="#top">▲</a> </p>
CSS Code:
This is css code to style back to top button.
#go-to-top { position: fixed; bottom: 30px; right: 15px; display:none; } #go-to-top a { background: #ef4748; color: #fff; width: 30px; height: 26px; border-radius: 5px; display: block; padding: 16px 10px 10px 12px; text-align: center; }
jQuery Code:
Scroll event works when user scroll down the page.The given below jquery code will display back to top button when user scroll down web page greater than 120px from top else will be hide.
//for fadein and fadeout top button $(window).scroll(function () { if ($(this).scrollTop() > 120) { $("#go-to-top").fadeIn(); } else { $("#go-to-top").fadeOut(); } });
This script will scroll up page smoothly when user clicks on back to top button. The jQuery animate() function and scrollTop events are used here to go back to top of page smoothly.
//scroll webpage body to top $("#go-to-top a").on("click", function () { $("body html").animate({scrollTop: 0}, 650); return false; });
Complete jQuery Code:
<script> //for fadein and fadeout back to top button $(window).scroll(function () { if ($(this).scrollTop() > 120) { $("#go-to-top").fadeIn(); } else { $("#go-to-top").fadeOut(); } }); //scroll webpage body to top $("#go-to-top a").on("click", function () { $("body html").animate({scrollTop: 0}, 650); return false; }); </script>
In this article you have learned about how to create scroll to top in jquery or how to create scroll to top button with jQuery.
If you have any query regarding this article please comment. I will gladly help you. PHPCluster.