Skip to content

Instantly share code, notes, and snippets.

@monaye
Last active October 4, 2018 02:57
Show Gist options
  • Select an option

  • Save monaye/3e941e69c4521c80f7678bc7e91017e1 to your computer and use it in GitHub Desktop.

Select an option

Save monaye/3e941e69c4521c80f7678bc7e91017e1 to your computer and use it in GitHub Desktop.
Add windows ScollTo event to all class
const targets = document.getElementsByClassName('smoothScroll');
const scrollToElement = function(event) {
event.preventDefault();
let elementId = event.target.attributes.href.value.replace('#', '');
let scrollPosition = document.getElementById(elementId).offsetTop;
window.scrollTo({
top: scrollPosition,
behavior: "smooth"
});
}
for(let i = 0; i < targets.length; i++){
targets[i].addEventListener('click', scrollToElement, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment