4
3

More than 5 years have passed since last update.

[メモ] JSで実装するidへのジャンプ

Posted at

クリックして指定のidへ飛ぶことをanchor scrollと呼びます。ライブラリを使っていれば実装されていることが多いですが、望む動きをしてくれなかったので、JSだけで実装する方法を検証します。

固定ヘッダーがない場合

const jumpTo = (id) => {
  const elem = document.getElementById(id);
  if (elem) {
    const top = elem.getBoundingClientRect().top;
    const newY = window.scrollY + top;
    console.log(newY);
    window.scrollTo(0, newY);
  }
}

jump_to_heading_1.gif
このサンプルのコードはこちらで確認できます。

固定ヘッダーがある場合

const HEADER_HEIGHT = 56;
const jumpTo = (id) => {
  const elem = document.getElementById(id);
  if (elem) {
    const top = elem.getBoundingClientRect().top;
    const newY = window.scrollY + top - HEADER_HEIGHT;
    console.log(newY);
    window.scrollTo(0, newY);
  }
}

jump_to_heading_2.gif
このサンプルのコードはこちらで確認できます。

とりあえずコードだけで。詳細なコードの説明は後ほど。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3