Created
April 13, 2015 22:54
-
-
Save JimBobSquarePants/952acdadc96302b79816 to your computer and use it in GitHub Desktop.
Smooth Scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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