The way this function will work:
1) The user clicks the button with ID “surf” and the animation begins
2) The function finds the first instance of div with class “threadboard,” pauses there for 1.5 seconds, then smoothly scrolls down to the next instance of a div with class “threadboard,” pauses there for 1.5s and then scrolls smoothly to the next, and so on
3) The function should do this through all the instances of divs with class “threadboard,” and then end
I’m trying to use jQuery with the methods scrollTop(), each(), animate() and setTimeout() so far with mixed success. Here’s what I have so far (EDIT: to include working but imperfect code):
var currentIndex = 0;
var numDivs = 18;
$(window).load(function() {
$('#surf').click(
function(){start();}
);
});
function start() {
//if (numDivs > 0) {
var winY = window.screenY;
$("body").animate({ scrollTop: 225 * currentIndex}, 1100);
//
currentIndex = (currentIndex + 1) % numDivs;
setTimeout(start, 3000);
//}
}
Right now I realize I’m kindof using a bootleg method by estimating that each instance is a certain number of pixels apart, and have hard-coded in the number of instances, which isn’t ideal. What is the best way to write this function? The code will be implemented at http://cornellhub.com/board/
Here’s my shot:
http://jsfiddle.net/3aBx9/
Basically, I check the top position of every existence of
.threadboard, iterate over each one, add a value to the timer and let it run.Creating a cancel button should be as simple as
clearTimeout().Final edit by original poster, with code modified that works in all browsers. The ultimate solution was to use
body, htmlinstead of eitherbodyorhtml, the former which works in webkit browsers and the latter which works in non-webkit browsers. The function and timeout also had to be moved out of the scope of the$(document).ready(function () {. The code below now reflects the edited solution: