Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar
Created June 25, 2015 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiegoSalazar/ee9c1efdf2336438f4a3 to your computer and use it in GitHub Desktop.
Save DiegoSalazar/ee9c1efdf2336438f4a3 to your computer and use it in GitHub Desktop.
window.lastScroll = 0;
$(function() {
var lastSnap, isAnimating,
snaps = $(".snap-to"),
$window = $(window);
var heights = snaps.map(function() {
return $(this).offset().top;
});
$window.scroll(function() {
var closestSnap = findSnapWithin(100, $window.scrollTop() + $window.height(), snaps);
if (closestSnap &&
closestSnap != lastSnap &&
!isAnimating &&
isScrollingDown($window.scrollTop())
) {
isAnimating = true;
lastSnap = closestSnap;
var top = $(closestSnap).offset().top;
$window.stop().scrollTo(top, 600, function() {
isAnimating = false;
})
}
});
});
function findSnapWithin(threshold, scrollTop, snaps) {
var foundSnap = snaps.filter(function() {
var top = $(this).offset().top;
if (top < scrollTop && top > scrollTop - threshold) {
return this;
}
});
return foundSnap[0];
}
function isScrollingDown(newScroll) {
if (newScroll > window.lastScroll) {
window.lastScroll = newScroll;
return true;
} else {
window.lastScroll = newScroll;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment