Skip to content

Instantly share code, notes, and snippets.

@Tiny-Giant
Created February 25, 2016 23:26
Show Gist options
  • Save Tiny-Giant/871ba884d1e02ef51337 to your computer and use it in GitHub Desktop.
Save Tiny-Giant/871ba884d1e02ef51337 to your computer and use it in GitHub Desktop.
document.addEventListener('click', function(e)
{
if (!/a/i.test(e.target.tagName))
{
return;
}
if (!/#/.test(e.target.href))
{
return;
}
var target = document.querySelector(/#[^?]+/.exec(e.target.href));
if (!target)
{
return;
}
e.preventDefault();
// Store the old top value.
var oldTop;
// Create an interval, so we can scroll in steps. We do this in 5ms intervals.
var scrollInterval = setInterval(function()
{
// Store the current offset from the top of the viewport to the top
// of the element. We can only scroll by a whole number, so round it down.
var top = Math.floor(target.getBoundingClientRect().top);
if (top === 0 || top === oldTop)
{
// If the offset is 0, or is the same as the old top value,
// clear the interval, and exit the function.
clearInterval(scrollInterval);
return;
}
// Store the current top value.
oldTop = top;
// Create our scrollBy variable.
var scrollBy;
if (top < 0)
{
// If top is a negative number, scroll by a negative number.
scrollBy = [-5, top][+(top > -5)];
}
else
{
// If top is a positive number, scroll by a positive number.
scrollBy = [5, top][+(top < 5)];
}
// Scroll our incrememnt.
window.scrollBy(0, scrollBy);
}, 5);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment