0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[jQuery] ページのトップに戻るボタンを作成する

Posted at

js形式のファイルを用意する

CDNを利用してjQueryを読み込み、js形式のファイルにコードを書いていきます。詳しくは以下で説明しています。
jQueryを使う準備をする

トップに戻るボタンをHTML、cssで作る

自分で好きなようにボタンを作ってください。Bootstrapやアイコンフォントなどを使ってもいいですね。
今回はトップに戻るボタンのクラス名を top-btn にしています。

js形式のファイルにコードを書く

js
$(function(){

  $('.top-btn').hide();
  
  $(window).scroll(function(){
    if($(this).scrollTop()>200){
      $('.top-btn').fadeIn();
    }else{
      $('.top-btn').fadeOut();
    }
  });

  $('.top-btn').click(function(){
    $('body,html').animate({scrollTop: 0},500);
    return false;
  });

});

上記のコードの説明です。↓

初めは、ボタンを表示させないようにします。

スクロール量が 200 になったらボタンを表示させます。
今回はスクロール量を 200 に設定しましたが好きな量に変更してください。

ボタンをクリックしたらスクロール量を 0 にします。(ページのトップに戻る)
戻る速度は 500 の速度に設定しましたが好きな速度に変更してください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?