<h1>ページ内リンクのURLに#を表示</h1>

<div>
  <a href="#target">ページ内リンク</a>
</div>

<div id="target">飛び先</a>
body {
  display: grid;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}
<script>
// ページ内リンクをクリックした時の処理
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        const targetId = this.getAttribute('href');
        const targetElement = document.querySelector(targetId);

        if (targetElement) {
            targetElement.scrollIntoView({
                behavior: 'smooth'
            });

            // URLにハッシュを追加
            history.pushState(null, '', targetId);
        }
    });
});

// ページロード時にURLのハッシュに基づいてスクロール
window.addEventListener('load', function() {
    if (window.location.hash) {
        const targetElement = document.querySelector(window.location.href);
        if (targetElement) {
            targetElement.scrollIntoView({
                behavior: 'smooth'
            });
        }
    }
});
</script>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.