Skip to content

Instantly share code, notes, and snippets.

@renoinn
Created July 15, 2020 06:37
Show Gist options
  • Select an option

  • Save renoinn/2d4671163d3b5c220ab33bce21e005ff to your computer and use it in GitHub Desktop.

Select an option

Save renoinn/2d4671163d3b5c220ab33bce21e005ff to your computer and use it in GitHub Desktop.
素のJSでスムーススクロールする
const links = document.querySelectorAll('a[href^="#"]')
for ( let i = 0; i < links.length; i++ ) {
links[i].addEventListener('click', (e) => {
e.preventDefault();
const target = document.querySelector(links[i].href.substr(links[i].href.indexOf('#')))
const elemY = target.getBoundingClientRect().top
const scrollY = window.pageYOffset
const top = Math.abs(elemY + scrollY)
console.log(`${elemY} - ${scrollY} = ${top}`)
window.scroll({
top: top,
behavior: 'smooth'
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment