Skip to content

Instantly share code, notes, and snippets.

@lukasbestle
Created September 6, 2013 12:28
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 lukasbestle/6e5459e15107b732c73c to your computer and use it in GitHub Desktop.
Save lukasbestle/6e5459e15107b732c73c to your computer and use it in GitHub Desktop.
Vanilla JS smooth scrolling
/**
* Vanilla JS smooth scrolling
*
* @version 0.1b1
* @author Lukas Bestle <lukas@lu-x.me>
* @copyright Lukas Bestle
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
// Configuration
var max = 50; // How many maximum steps
var time = 300; // How many milliseconds?
var smoothScroll = function(element, pixels, count) {
// Increase recursion count
count += 1;
// Check if it scrolled to often (maybe the user scrolled manually or so)
if(count > max) {
return;
}
// Get the current positions
var container = element.parentNode;
var current = container.scrollTop;
var destination = element.offsetTop;
if(destination == current) {
// Finished, set hash
setTimeout(function() {
if(element.id) window.location.hash = element.id;
}, 100);
return;
}
// Calculate difference per step (20 steps)
if(!pixels) pixels = parseInt((destination - current) / 20, 10);
// Check how near we are and reduce the speed over time (easing, yehaa!)
var pixelsAbs = Math.abs(pixels);
if(Math.abs(destination - current) < 2 * pixelsAbs && pixelsAbs > 1) pixels = parseInt(pixels / 2);
// Scroll the container
container.scrollTop += pixels;
// Wait the time and scroll further
setTimeout(function() {
smoothScroll(element, pixels, count);
}, time / 20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment