/ Published in: JavaScript
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
Requires JQuery but can easily be adapted to other JS framework
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// "go to top" link on window scroll var topdistant = false; function getScrollY() { var scrOfY = 0; //, scrOfX = 0; if( typeof( window.pageYOffset ) == 'number' ) { scrOfY = window.pageYOffset; //scrOfX = window.pageXOffset; } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { scrOfY = document.body.scrollTop; //scrOfX = document.body.scrollLeft; } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { scrOfY = document.documentElement.scrollTop; //scrOfX = document.documentElement.scrollLeft; } return scrOfY; } function topDistanceCrosses(distance){ if (getScrollY() > distance && !topdistant) { topdistant = true; $("#toplink").slideDown('slow'); return 1 ; // going down } else if(getScrollY() < distance && topdistant ) { topdistant = false; $("#toplink").slideUp('fast'); return 2; // going up } else { return 0; // nothing happens } } on HTML could be something like: ... <body onload="topDistanceCrosses(200)" onscroll="topDistanceCrosses(200)"> ... <a href="#"> <div id="toplink"> Back to top � </div> </a> on CSS could be something like: #toplink { position: fixed; bottom: 0px; background-color: #f0deae; display: none; width: 100px; height: 20px; text-align: center; margin-left: -120px; float: left; }