Scroll-to-Top and Scroll-to-Bottom Effects - jQuery Anchor Navigation Compatible with All Browsers

Scroll-to-top and scroll-to-bottom functionality is widely used on web pages.
For a better user experience, we use smooth scrolling when returning to the top or bottom of a page.
For this, we can use the powerful jQuery library. The specific steps are as follows:
1. Add the following code anywhere inside the page's body element.
1 2 3 4 5 6 7 8 9 10 11 | <div id="scroll"> <div id="toTop" class="scrollItem"> Back to Top </div> <div id="toBottom" class="scrollItem"> Back to Bottom </div> </div> |
Add the CSS to the head section.
1 2 | #scroll {position:fixed; top:300px; right:100px;}.scrollItem {width:20px; height:70px;border:#e1e1e1 1px solid; cursor: pointer; text-align: center; padding-top: 10px;} |
Of course, you can also customize the appearance by using your own image. The key is to keep the ID consistent with the JavaScript code and set the position of the scroll navigation layer to fixed. This ensures that the navigation layer stays in place when the scrollbar is moved.
2. Include the jQuery library file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <script type="text/javascript">// <![CDATA[ $( function () { var speed = 1000;// Custom scroll speed // Back to Top $( "#toTop").click( function () { $( "html,body").animate({ "scrollTop" : 0 }, speed); }); // Back to Bottom var windowHeight = parseInt($("body").css("height" ));// Total page height $( "#toBottom").click(function () { $( "html,body").animate({ "scrollTop" : windowHeight }, speed); }); }); // ]]></script> |
In the JavaScript code above, you can customize the scrolling speed. The larger the speed value, the faster the scrolling.
var speed = 1000;
Your page will then support scrolling back to the top and bottom.
I would also like to add another feature: scrolling to an element with a specified ID. The syntax is as follows. Set scrollTop to
$(‘#ID’).offset().top
If you are a website administrator, you can add the above code to your footer template (usually footer.php), enabling this functionality on every page of your website.
Download Link (Includes JavaScript Files and Demo)