Skip to content

Instantly share code, notes, and snippets.

@austinpray
Last active October 22, 2021 20:27
Show Gist options
  • Save austinpray/5994652 to your computer and use it in GitHub Desktop.
Save austinpray/5994652 to your computer and use it in GitHub Desktop.
Zepto.js smooth vertical scrolling method. Implementing this code turns all anchor links with the class "scrollTo" into smooth scrolling anchor links. Rework of the foundation.js library method.
function smoothScroll(el, to, duration) {
if (duration < 0) {
return;
}
var difference = to - $(window).scrollTop();
var perTick = difference / duration * 10;
this.scrollToTimerCache = setTimeout(function() {
if (!isNaN(parseInt(perTick, 10))) {
window.scrollTo(0, $(window).scrollTop() + perTick);
smoothScroll(el, to, duration - 10);
}
}.bind(this), 10);
}
$('.scrollTo').on('click', function(e) {
e.preventDefault();
smoothScroll($(window), $($(e.currentTarget).attr('href')).offset().top, 200);
});
@pbpyrojust
Copy link

This is the console error when I use your script. Why are you using .scrollTop on line 5?
Uncaught TypeError: Object # has no method 'scrollTop'

@landys
Copy link

landys commented Jan 11, 2015

Thanks. It works well for me.

@rdyson
Copy link

rdyson commented May 10, 2017

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment