勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ

アンカーリンクでURLに「#hoge」のようなパラメータを残さずスクロールさせる方法

  jQuery JavaScript

アンカータグをクリックしてもブラウザのURL欄に「#hoge」のようなハッシュを残さずに指定の要素までスクロールできるというコーディングデータがあった。しかも他ページからハッシュ付きのURLで遷移してきてもスクロール後にハッシュが消えるような挙動を取っており、どういう手段なのか気になったのでメモ。

 

サンプル

https://taitan916.info/sample/anchor_link/

 

ソースコード

<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>アンカータグでスクロールテスト</title>
</head>
<body>
    <a href="#test1">test1</a>
    <a href="#test2">test2</a>
    <a href="#test3">test3</a>
    <div style="background-color: #f00; height: 1000px;" id="test1"></div>
    <div style="background-color: #0f0; height: 1000px;" id="test2"></div>
    <div style="background-color: #00f; height: 1000px;" id="test3"></div>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript">
    $(function(){

        const hash = decodeURI(location.hash);
        if(hash){
            $("html, body").animate({scrollTop:$(hash).offset().top});
            window.history.replaceState(null, '', window.location.pathname + window.location.search);
        }

        $('a[href^="#"]').click(function(){
            const href= $(this).attr("href");
            const target = $(href == "#" || href == "" ? 'html' : href);
            $("html, body").animate({scrollTop:target.offset().top});
            window.history.replaceState(null, '', window.location.pathname + window.location.search);
            return false;
        });
    });
    </script>
</body>
</html>

他ページから遷移してきた際は「if(hash){」のところで、リンクをクリックした際は「$('a[href^="#"]').click(function(){」で検知しスクロールした後にpushStateでハッシュを削除している。尚、ハッシュは特に削除しなくてもいい場合は以下の形でOK。

$(function(){
    $('a[href^="#"]').click(function(){
        const href= $(this).attr("href");
        const target = $(href == "#" || href == "" ? 'html' : href);
        $("html, body").animate({scrollTop:target.offset().top});
        return false;
    });
});

 

所感

URLはできるだけシンプルな方が良い派なので今後も使っていきたいところ。

 - jQuery JavaScript

  関連記事

指定した要素に注釈を設定できる「Chardin.js」プラグインの利用方法
指定した要素に注釈を設定できる「Chardin.js」プラグインの利用方法

指定した要素に注釈を入れることができるjQueryプラグイン「Chardin.j ...

jQueryで指定の行動をとった際に、クリックイベントを発火させる方法
jQueryで指定の行動をとった際に、クリックイベントを発火させる方法

あるシステムでAという要素をクリックした際に何らかの処理を行うという部分があり、 ...

jQueryでAjax通信したデータをPHPで受け取り、zip化したファイルをダウンロードさせる方法
jQueryでAjax通信したデータをPHPで受け取り、zip化したファイルをダウンロードさせる方法

jQueryのAjaxで何らかのデータをPHP側に送信し、PHP側で当該データを ...

summernote(WYSIWYGエディタ)の設置方法と日本語化対応
summernote(WYSIWYGエディタ)の設置方法と日本語化対応

あるシステムにWYSIWYGエディタを実装したかった。以前にメモしたCKEdit ...

JavaScript / jQueryにてページ表示時に指定したテキストボックスにフォーカスさせる方法
JavaScript / jQueryにてページ表示時に指定したテキストボックスにフォーカスさせる方法

ページを開いた際に指定したテキストボックス(input type="text") ...