Create a Simple Back to Top Button with jQuery
We've all seen those handy little "back to top" buttons, the one that usually appear at the bottom of a page once a user starts scrolling that, when clicked, will smoothly return the page back to the top position.
Insert the following snippet into your projects to add a back to top button to your own pages. The code works by having the button (in this case it's the element with the class .back-to-top) initially hidden, with instructions to .fade-in() once the user has scrolled past 100px. Have fun styling your button any way you like!
$(document).ready(function(){ var $backToTop = $(".back-to-top"); /* this hides the back to top button when the page first loads */ $backToTop.hide();
/* now we need to write a function that makes the back to top button appear after the user has scrolled a certain amount */ $(window).on('scroll', function() { if ($(this).scrollTop() > 100) { /* back to top will appear after the user scrolls 100 pixels */ $backToTop.fadeIn(); } else { $backToTop.fadeOut(); } });
/* this function activates a smooth scroll to the top of the page when the back to top button is clicked */ $backToTop.on('click', function(e) { $("html, body").animate({scrollTop: 0}, 500); }); })