7
7

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.

【Ruby on Rails】トップに戻るボタン

Last updated at Posted at 2020-09-25

目標

arrow.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

※ ▶◯◯ を選択すると、説明等が出てきますので、
  よくわからない場合の参考にしていただければと思います。

上記機能はなくても大丈夫です。

流れ

1 写真の用意
2 viewの編集
3 cssの編集
4 jsファイルの編集(ページスクロールにアニメーションを追加する場合)

写真の用意

このような画像を用意してください。
ちなみにこの画像はipadで作成しましたので、ご自由にお使いください。
arrow.jpg

画像ファイルをapp/assets/images配下に格納してください。

viewの編集

今回は全てのページで表示したいため、下記場所に記載。

app/views/layouts/application.html.erb
<body>
  <%= yield %>
  <span id="back">
    <a href="">
      <%= image_tag asset_path('arrow.jpg'), data: {"turbolinks"=>false}, class: "arrow" %>
    </a>
  </span>
</body>
補足【image_tag asset_path( )】 app/assets/images配下の画像を読み込むことが出来ます。
補足【data: {"turbolinks"=>false}】 turbolinksの誤作動を防ぎます。

cssの編集

app/application.css
#back {
  position: fixed;
  right: 20px;
  bottom: 20px;
}
.arrow{
  width:      50px;
  height:     50px;
}
補足【position: fixed;】 position: fixed;により表示する場所を固定しています。

jsファイルの編集

gem 'jquery-rails'を導入しておいてください。
マウスでクリックするとアニメーションを動作させます。

app/assets/javascripts/application.js
$(function() {
  $('#back a').on('click',function(event){
    $('body, html').animate({
      scrollTop:0
    }, 800);
    event.preventDefault();
  });
});

補足【$('#back a').on('click',function(event)】 $('.セレクタ名').on('click',function(event) {   イベント発生時に行われる処理 });
補足【$('body, html').animate】 $('セレクタ名').animate({    変化対象のプロパティ名:変化値   }, アニメーションの動作時間); 
7
7
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
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?