In my current solution to scroll from a div to another div I support both previous
and next
.
This works by saving the index of the div last scrolled to in order to determine where to scroll to next. However this breaks when users scroll with their wheel. I was wondering if there is a way to calculate which div is the closest to the top of the window, to then determine which index to scroll to next.
This in return would remove the issues that I'm having.
Test error using my current solution:
- Go to the jsfiddle link
- Click the down arrow twice. It should scroll from one div to the next.
- Next, using the wheel on your mouse scroll down 3/4 of the page.
- Now hit the down arrow again. You'll see it takes you back to the top where you last left off stepping down.
http://jsfiddle.net/JokerMartini/yj9pvz2a/1/
var curr_el_index = 0;
var els_length = $(".section").length;
$('.btnNext').click(function () {
curr_el_index++;
if (curr_el_index >= els_length) curr_el_index = 0;
$("html, body").animate({
scrollTop: $(".section").eq(curr_el_index).offset().top - 20
}, 700);
});
$('.btnPrev').click(function () {
curr_el_index--;
if (curr_el_index < 0) curr_el_index = els_length - 1;
$("html, body").animate({
scrollTop: $(".section").eq(curr_el_index).offset().top - 20
}, 700);
});
Solution Updated: http://jsfiddle.net/JokerMartini/82wo9e3c/1/