Reputation: 13
I want to create a Jquery script that scrolls down to the next div down below, whenever user clicks.
I have an array of pixel offsets of each DIV from the top.
I dont' know how to loop or
count the number of clicks.
jQuery(document).ready(function(){
var move=[0,642,1725,2393,3036,6097,6991];
var i=0;
var duration = 500;
jQuery(".next").click(function(){
//event.preventDefault();
jQuery('html, body').animate({scrollTop: move[i]+'px'}, duration);
})
});
Upvotes: 0
Views: 474
Reputation: 57105
Try i = (i == 7)?i=0:i;
and move[i++]
jQuery(document).ready(function () {
var move = [0, 642, 1725, 2393, 3036, 6097, 6991];
var i = 0;
var duration = 500;
jQuery(".next").click(function () {
//event.preventDefault();
i = (i == 7)?i=0:i;
jQuery('html, body').animate({
scrollTop: move[i++] + 'px' //set current value and increment it by 1
}, duration);
})
});
Upvotes: 1
Reputation: 53246
Just increment it in the handler?
$(function() {
var move=[0,642,1725,2393,3036,6097,6991],
i = 0,
duration = 500;
$('.next').on('click', function(e) {
e.preventDefault();
$('html, body').animate({scrollTop: move[i]+'px'}, duration);
i++;
});
});
I'd be tempted to have jQuery fetch the offset().top
positions of the elements you want to scroll to though, otherwise you'll need to change the array values every time your code or content is modified...
You'll also likely need do some checking within the function callback to avoid an overflow:
$(function() {
var move=[0,642,1725,2393,3036,6097,6991],
i = 0,
duration = 500;
$('.next').on('click', function(e) {
e.preventDefault();
if(i < move.length)
{
$('html, body').animate({scrollTop: move[i]+'px'}, duration);
i++;
}
});
});
Upvotes: 1