Skip to content

Instantly share code, notes, and snippets.

@gillesv
Created December 13, 2012 16:43
Show Gist options
  • Save gillesv/4277801 to your computer and use it in GitHub Desktop.
Save gillesv/4277801 to your computer and use it in GitHub Desktop.
2 JQuery scrolling methods I use. Scroll to a position in pixels, or scroll to an element. Duration of scrolling animation is calculated dynamically based on how many pixels the viewport has to travel. Fiddle with the math on line 5 to tweak the speed to your liking.
// scrolling methods: scroll to pixels
function scrollViewTo(target, callback) {
var duration, pos;
pos = $body.scrollTop();
duration = ((Math.abs(pos - target) / 1000) * 1000);
$("html:not(:animated),body:not(:animated)").animate({scrollTop: target + 'px'}, duration, callback);
}
// scroll to element
function scrollTo(elementSelector, callback) {
var top;
top = $(elementSelector).offset().top;
scrollViewTo(top, callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment