Skip to content

Instantly share code, notes, and snippets.

@webmasterMeyers
Last active April 1, 2021 18:27
Show Gist options
  • Save webmasterMeyers/173ce88558756918e76418c68e1d94d1 to your computer and use it in GitHub Desktop.
Save webmasterMeyers/173ce88558756918e76418c68e1d94d1 to your computer and use it in GitHub Desktop.
Add this script file to either the `<head>` section or before the `</body>` tag. It will automatically smooth scroll to your anchor tags (id's) when clicking a link targeting them in the `href=""`. Insparation, and original scripts taken from https://gist.github.com/benjamincharity/6058688 and https://gist.github.com/madrobby/8507960
;(function($){
$.fn.scrollToTop = function(position){
var $this = this,
targetY = position || 0,
initialY = $this.scrollTop(),
lastY = initialY,
delta = targetY - initialY,
speed = Math.min(1500, Math.min(2000, Math.abs(initialY-targetY))),
start, t, y, frame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){ setTimeout(callback,15) },
cancelScroll = function(){ abort() }
if (delta == 0) return
function smooth(pos){
if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,5)
return 0.5 * (Math.pow((pos-2),5) + 2)
}
function abort(){
$this.off('touchstart', cancelScroll)
}
$this.on('touchstart', cancelScroll)
frame(function render(now){
if (!start) start = now
t = Math.min(1, Math.max((now - start)/speed, 0))
y = Math.round(initialY + delta * smooth(t))
if (delta > 0 && y > targetY) y = targetY
if (delta < 0 && y < targetY) y = targetY
if (lastY != y) $this.scrollTop(y)
lastY = y
if (y !== targetY) frame(render)
else abort()
})
}
})(Zepto)
Zepto(function($) {
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
$(window).scrollToTop($($(e.currentTarget).attr('href')).offset().top);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment