Created
September 6, 2013 12:28
-
-
Save lukasbestle/6e5459e15107b732c73c to your computer and use it in GitHub Desktop.
Vanilla JS smooth scrolling
This file contains hidden or 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
/** | |
* Vanilla JS smooth scrolling | |
* | |
* @version 0.1b1 | |
* @author Lukas Bestle <[email protected]> | |
* @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