Skip to content

Instantly share code, notes, and snippets.

@carrieforde
Last active October 17, 2017 19:08
Show Gist options
  • Save carrieforde/8d8867bd561484b27aa511d0ced323ef to your computer and use it in GitHub Desktop.
Save carrieforde/8d8867bd561484b27aa511d0ced323ef to your computer and use it in GitHub Desktop.
Smooth scroll
/**
* Add smooth scrolling for on-page navigation.
*/
(function() {
// Script options.
var options = {
menuSelector: '.site-navigation ul',
mobileBreakPoint : 900,
headerHeight: 0,
timeout: 500 // in milleseconds
},
menu = document.querySelector(options.menuSelector);
/**
* Do smooth scrolling.
*
* @param {any} event
*/
function smoothScroll( event ) {
event.preventDefault();
var el = event.target,
hash = el.getAttribute('href'),
url = window.location.pathname,
target = document.querySelector(hash),
offset = target.offsetTop;
// Check window width, and update offset accordingly.
if (window.innerWidth > options.mobileBreakPoint - 1) {
offset = offset - options.headerHeight;
}
// Scroll the the desired element.
window.scroll({left: 0, top: offset, behavior: 'smooth'});
// Update focus after scolling is complete.
setTimeout(function () {
// Updates focus to our target element.
target.setAttribute('tabindex', '-1');
target.focus();
// Because we prevented the default action, we have to update the URL manually.
window.location.href = url + hash;
// Prevents jumpbacks from applying focus.
window.scroll(0, offset);
}, options.timeout);
}
menu.addEventListener('click', smoothScroll);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment