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

Target

arrow.gif

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

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

flow

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.

erb: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>
Supplement [image_tag asset_path ()] Images under app / assets / images can be read.
Supplement [data: {"turbolinks" => false}] Prevents turbolinks from malfunctioning.

Editing css

app/application.css


#back {
  position: fixed;
  right: 20px;
  bottom: 20px;
}
.arrow{
  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.

app/assets/javascripts/application.js


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

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