Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created April 13, 2015 22:54
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 JimBobSquarePants/952acdadc96302b79816 to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/952acdadc96302b79816 to your computer and use it in GitHub Desktop.
Smooth Scroll
if (window.jQuery) {
(function ($, w, d) {
var $d = $(d);
$d.ready(function () {
$d.on("click", "a[data-smooth-scroll]", function (event) {
var $this = $(this),
href = $this.attr("href");
if (href.indexOf("#") === 0) {
event.preventDefault();
var scrollTop = $(w).scrollTop(),
height = parseInt($d.height(), 10),
offset = $(href).offset().top,
speed = $this.data("scrollSpeed");
if (!speed) {
$this.data("scrollSpeed", (speed = 1000))
}
// Normalise the speed of scroll.
var distance = scrollTop - offset;
// Make sure the distance is always positive.
if (distance < 0) {
distance *= -1;
}
// v = d/t - multiply for milliseconds.
var time = (distance / height) * speed,
called = false;
$("html, body").animate({
scrollTop: offset
}, {
duration: time,
complete: function () {
// Prevent dupliction of complete call by binding to both html and body.
if (!called) {
called = true;
w.location.hash = href;
}
}
});
}
});
});
}(jQuery, window, document));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment