Smooth Scroll to Top Function


/ Published in: jQuery
Save to your folder(s)

Hides the button based on scroll position, fades in and out as necessary and upon click smoothly scrolls back to the top.


Copy this code and paste it in your HTML
  1. $(document).ready(function() {
  2.  
  3. // hide #back-top first
  4. $("#back-top").hide();
  5.  
  6. // fade in #back-top
  7. $(function() {
  8. $(window).scroll(function() {
  9. if ($(this).scrollTop() > 100) {
  10. $('#back-top').fadeIn();
  11. } else {
  12. $('#back-top').fadeOut();
  13. }
  14. });
  15.  
  16. // scroll body to 0px on click
  17. $('#back-top a').click(function() {
  18. $('body,html').animate({
  19. scrollTop: 0
  20. }, 800);
  21. return false;
  22. });
  23. });
  24.  
  25. });​
  26.  
  27.  
  28. HTML USAGE:
  29.  
  30. <p id="back-top" style="display: block; ">
  31. <a href="#top"><span></span><em>Back to top</em></a>
  32. </p>

URL: http://www.pixeltweaks.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.