I'm trying to figure out how to, upon pageload, automatically scroll to the bottom of a page (which has been described sufficiently here) and then scroll back up automatically upon reaching the bottom of the page. I can find the automatic scrolling to the bottom, but I can't figure out how to identify when I'm at the bottom of the page, and how to scroll back up when I am. I'd do this using generic Javascript (or JQuery).
Thanks in advance!
Try this:
http://jsfiddle.net/yjYJ4/
$('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 1000, function() {
$(this).animate({ scrollTop: 0 }, 1000);
});
You can view the demo in full screen here: http://jsfiddle.net/yjYJ4/embedded/result/
Change the number "1000" if you want to increase or decrease speed.
Works fine in Chrome, Firefox and IE 6-9.
EDIT:
If you need it to repeat forever (not recommended...) you could do like this: http://jsfiddle.net/QUCWe/
here is the example using Pure JavaScript
<script type="application/javascript">
var Height = document.documentElement.scrollHeight;
var currentHeight = 0;
var bool = true;
var step = 5;
var speed = 10;
var interval = setInterval(scrollpage, speed)
function scrollpage() {
if (currentHeight < 0 || currentHeight > Height)
bool = !bool;
if (bool) {
window.scrollTo(0, currentHeight += step);
} else {
// if you don't want to continue scroll
// clearInterval(interval) use clearInterval
window.scrollTo(0, currentHeight -= step);
}
}
</script>
<style type="text/css">
#top {
border: 1px solid black;
height: 10000px;
}
#bottom {
border: 1px solid red;
}
</style>
<div id="top">top</div>
<div id="bottom">bottom</div>
You can pass a function as an argument, which will be called when the end has reached. I've just written a jQuery plugin for this purpose. Fiddle: http://jsfiddle.net/kKaWZ/
(function($){
$.fn.downAndUp = function(time, repeat){
var elem = this;
(function dap(){
elem.animate({scrollTop:elem.outerHeight()}, time, function(){
elem.animate({scrollTop:0}, time, function(){
if(--repeat) dap();
});
});
})();
}
})(jQuery);
$("html").downAndUp(2000, 5)
Be aware that the suggested infinite scroll JSFiddle code will work in firefox however will not work in Chrome/Chromium without a valid
tag at the start of ones page. Per This Answer
$("body").animate({ scrollTop: '1000' }, 500, function(){
$("body").animate({ scrollTop: '0' }, 500, function(){
$("body").animate({ scrollTop: '1000' }, 500);
});
});