Skip to content

Instantly share code, notes, and snippets.

@space11
Created October 14, 2018 13:03
Show Gist options
  • Save space11/b1571633e108f5f5688a497eb629fc89 to your computer and use it in GitHub Desktop.
Save space11/b1571633e108f5f5688a497eb629fc89 to your computer and use it in GitHub Desktop.
Vanilla JS c smooth scroll
/*
For some time, you DON'T need jQuery to make simple but beauty smooth scroll on your website.
I realize that there are several ideas of this code on the Internet,
but I have a need to resurface everything that is most important in one file.
*/
// Find all links with href attribute which is beginning at '#"
// ( example: #about -> that means it take us to element with id about )
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
/* Below is very important code (I think that a lot of developers usually forhet about it )
After jump to element, we should inform about our step, adding id to the current website link. */
history.pushState(null, null, anchor.getAttribute("href"));
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth', // if we want to jump smoothly
block: 'start' // if we want to jump to the begin of element
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment