Automatic "Back to Top" link when scrolling down


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

this script brings you a "back to top" when you cross the vertical threshold defined as argument on the body tag (e.g.: 200px)

Requires JQuery but can easily be adapted to other JS framework


Copy this code and paste it in your HTML
  1. // "go to top" link on window scroll
  2. var topdistant = false;
  3.  
  4. function getScrollY() {
  5. var scrOfY = 0; //, scrOfX = 0;
  6. if( typeof( window.pageYOffset ) == 'number' ) {
  7. scrOfY = window.pageYOffset; //scrOfX = window.pageXOffset;
  8. } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
  9. scrOfY = document.body.scrollTop; //scrOfX = document.body.scrollLeft;
  10. } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
  11. scrOfY = document.documentElement.scrollTop; //scrOfX = document.documentElement.scrollLeft;
  12. }
  13. return scrOfY;
  14. }
  15.  
  16. function topDistanceCrosses(distance){
  17. if (getScrollY() > distance && !topdistant) {
  18. topdistant = true;
  19. $("#toplink").slideDown('slow');
  20. return 1 ; // going down
  21. }
  22. else if(getScrollY() < distance && topdistant ) {
  23. topdistant = false;
  24. $("#toplink").slideUp('fast');
  25. return 2; // going up
  26. }
  27. else {
  28. return 0; // nothing happens
  29. }
  30. }
  31.  
  32. on HTML could be something like:
  33. ...
  34. <body onload="topDistanceCrosses(200)" onscroll="topDistanceCrosses(200)">
  35. ...
  36. <a href="#">
  37. <div id="toplink">
  38. Back to top �
  39. </div>
  40. </a>
  41.  
  42. on CSS could be something like:
  43. #toplink {
  44. position: fixed;
  45. bottom: 0px;
  46. background-color: #f0deae;
  47. display: none;
  48. width: 100px;
  49. height: 20px;
  50. text-align: center;
  51. margin-left: -120px;
  52. float: left;
  53. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.