Jquery Scrolltop() Returns Wrong Offset On Scroll-direction Change
I'm trying to get the correct scroll direction via jQuery's 'scroll' event. For this, I'm using the solution here: https://stackoverflow.com/a/4326907/8407840 However, if I change
Solution 1:
The problem lies in the assignment prevPosition = ctPosition
.
Each time the scroll handler runs, var ctPosition = $(window).scrollTop();
is good for determining scroll direction, however it's not the value that should be rememberad as prevPosition
.
prevPosition
needs to be $(window).scrollTop()
as measured after the animation has completed.
Try this :
$(document).ready(function() {
varANIMATION_DURATION = 700;
varACTIVE_SECTION = $("section:first-of-type").eq(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", doScrollingStuff);
functiondoScrollingStuff(e) {
$(window).off("scroll");
var ctPosition = $(window).scrollTop();
var nextSection = (ctPosition < prevPosition) ? ACTIVE_SECTION.prev("section") : (ctPosition > prevPosition) ? ACTIVE_SECTION.next("section") : ACTIVE_SECTION; // Determine scroll direction and target the next section// If next section exists and is not current section: Scroll to it!if(nextSection.length > 0 && nextSection !== ACTIVE_SECTION) {
$("body, html").animate({
'scrollTop': nextSection.offset().top
}, ANIMATION_DURATION).promise().then(function() {
// when animation is complete
prevPosition = $(window).scrollTop(); // remember remeasured .scrollTop()ACTIVE_SECTION = nextSection; // remember active section
$(window).on("scroll", doScrollingStuff); // no need for additional delay after animation
});
} else {
setTimeout(function() {
$(window).on("scroll", doScrollingStuff);
}, 100); // Debounce
}
}
});
Post a Comment for "Jquery Scrolltop() Returns Wrong Offset On Scroll-direction Change"