scrollIntoViewとは
呼び出された要素がユーザーに見えるところまでスクロールするメソッド。
オプションで「behavior: 'smooth'」を指定すればスムーススクロールになる。
const target = document.getElementById('foo')
target.scrollIntoView({
behavior: 'smooth'
})
Safariにも対応
MDNやCan I useには最新のSafari (バージョン15.5)ではscrollIntoViewのsmoothオプションは使用不可と書かれているが、実際はSafariでも動作します。
scrollIntoViewの使い方
Webサイトではリンクの「a[href^="#"]」をクリックして指定したidのところまでスムーススクロールを行うケースが多い。
そのため、以下のように「a[href^="#"]」がクリックされた際にscrollIntoViewを使用して該当要素にスムーススクロールように処理を書けば簡単に実装できる。
<style>p { margin-bottom: 200px; }</style>
<h1 id="top">top</h1>
<a href="#bottom">go to #bottom</a>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<h2 id="bottom">bottom</h2>
<a href="#top">go to #top</a>
const links = document.querySelectorAll('a[href^="#"]')
links.forEach((el) => {
el.addEventListener('click', (e) => {
e.preventDefault()
const href = el.getAttribute('href')
const target = document.getElementById(href.replace('#', ''))
target.scrollIntoView({
behavior: 'smooth'
})
})
})
scrollIntoViewでスムーススクロールを実装したサンプル