Skip to content

Instantly share code, notes, and snippets.

@serweb-labs
Last active February 7, 2018 17:14
Show Gist options
  • Save serweb-labs/dc70571be3d2663cf373a7f9a480835d to your computer and use it in GitHub Desktop.
Save serweb-labs/dc70571be3d2663cf373a7f9a480835d to your computer and use it in GitHub Desktop.
smooth scroll
// for jquery
$( document ).ready(function() {
$(".smoothScroll").on('click', function(e){
smoothScroll(e);
})
});
window.jump = function(target, options) {
options = options || {};
var t = document.querySelector(target);
if (t == null) return;
var start = window.pageYOffset,
opt = {
duration: options.duration || 100,
offset: options.offset || 0,
callback: options.callback,
easing: options.easing || easeInOutQuad
},
distance = typeof target === 'string'
? opt.offset + t.getBoundingClientRect().top
: target,
duration = typeof opt.duration === 'function'
? opt.duration(distance)
: opt.duration,
timeStart, timeElapsed
;
requestAnimationFrame(function(time) { timeStart = time; loop(time); });
function loop(time) {
timeElapsed = time - timeStart;
window.scrollTo(0, opt.easing(timeElapsed, start, distance, duration));
if (timeElapsed < duration)
requestAnimationFrame(loop)
else
end();
}
function end() {
window.scrollTo(0, start + distance);
if (typeof opt.callback === 'function')
opt.callback();
}
// Robert Penner's easeInOutQuad - http://robertpenner.com/easing/
function easeInOutQuad(t, b, c, d) {
t /= d / 2
if(t < 1) return c / 2 * t * t + b
t--
return -c / 2 * (t * (t - 2) - 1) + b
}
}
window.smoothScroll = function (e, offset) {
e.stopPropagation();
e.preventDefault();
offset = offset || -50;
var vm = this;
var hash = e.target.hash || e.currentTarget.hash
jump(hash, {
duration: 400,
offset: offset,
callback: function() {}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment