As a way to learn more about jQuery, I'm trying to make a function that will scroll to the bottom of the page, back to the top and then start again in an infinite loop.
so far I have got this
var scroll = $(document).scrollTop();
setInterval(function(){
scroll += 5;
$(document).scrollTop(scroll);
}, 10);
This will scroll to the bottom of the page.
When it hits the bottom it needs to set a flag, maybe var direction = 1
where 1 is down and 0 is up.
Now I need to add something like
if(direction){
// scroll down
} else {
// scroll up
}
So I the IF would constantly check the value of direction and increment the scroll var by either += 5 or -=5
Does that sound logical or is there a much simpler way to achieve this?
EDIT
Here is a working version of somethinghere's suggestion
https://jsfiddle.net/Panomosh/evkxou3e/
You should use jQuerys callback to create an infinitely recursing function. Just add a function after the declaration in your animate function, and then call the same function, but invert the passed boolean.
Also, animate will do this incrementing very nice and smoothly for you!
function scrollTopOrBottom(top){
if(top) $("body, html").animate({scrollTop: 0}, function(){
scrollTopOrBottom(false);
});
else $("body, html").animate({scrollTop: $("document").height()}, function(){
scrollTopOrBottom(true);
});
}
scrollTopOrBottom(false);
Update: As mentioned, this could create a * * ahem * * Stack Overflow, but the question is not concerned with that at this point. If you want to be safe, use a stop() after each $("body, html") statement to stop the call from proceeding if another one is in progress, therefore deferring overflow.
Note: You could also wrap the if statement in {} but since it's one statement I find it a bit more legible, more sentence-like than code-like. But thats preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With