[JAVA] [Ruby on Rails] Button to return to top



Development environment

ruby 2.5.7 Rails OS: macOS Catalina


-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)

You do not need to have the above functions.


1 Preparation of photo 2 Edit view 3 Edit css 4 Edit js file (when adding animation to page scroll)

Preparation of photos

Please prepare an image like this. By the way, this image was created with ipad, so feel free to use it. arrow.jpg

Please store the image file under app / assets / images.

edit view

Since I want to display it on all pages this time, I will describe it in the following location.


  <%= yield %>
  <span id="back">
    <a href="">
      <%= image_tag asset_path('arrow.jpg'), data: {"turbolinks"=>false}, class: "arrow" %>
Supplement [image_tag asset_path ()] Images under app / assets / images can be read.
Supplement [data: {"turbolinks" => false}] Prevents turbolinks from malfunctioning.

Editing css


#back {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width:      50px;
  height:     50px;
Supplement [position: fixed;] The position to be displayed is fixed by position: fixed ;.

Edit js file

Please install gem'jquery-rails'. Click with the mouse to activate the animation.


$(function() {
  $('#back a').on('click',function(event){
    $('body, html').animate({
    }, 800);

Supplement [$ ('# back a'). On ('click', function (event)] $ ('. Selector name'). On ('click', function (event) { Processing performed when an event occurs });
Supplement [$ ('body, html'). Animate] $ ('Selector name'). animate ({ Property name to be changed: Change value }, Animation operating time);

Recommended Posts