Back to top button made only with Javascript (rails, haml)

■ Introduction

I wrote an article about the back to top button made only with Javascript. Here's what you'll get in this article:

・ Increase basic knowledge of Javascript ・ You will be able to understand how to create a button to return to the top using Javascript without depending on jQuery.

・ Sites and videos that I referred to → [If you scroll with JS, ◯◯! Let's process it by linking it to the scroll! ](Https://www.youtube.com/watch?v=_agZ_AP6W44&ab_channel=%E3%83%95%E3%83%AD%E3%83%B3%E3%83%88%E3%82%A8%E3 % 83% B3% E3% 83% 89% E3% 83% 81% E3% 83% A3% E3% 83% B3% E3% 83% 8D% E3% 83% AB-% E5% 9F% BA% E7% A4% 8E% E3% 81% 8B% E3% 82% 89% E5% BF% 9C% E7% 94% A8% E3% 81% BE% E3% 81% A7-% E6% AD% A6% E7% 94 % B0% E4% B8% 80% E7% 9C% 9F) → [De-jQuery] Implemented a button to return to the top with Javascript only

■ Code

haml:index.html.haml


.scroll#scrollValue
  %i.fas.fa-angle-up

= javascript_pack_tag 'main' -# app/javascript/packs/home/main.read js

index.scss


.scroll {
  position: fixed;
  right: 0;
  bottom: 0;
  font-size: 2rem;
  color: #fff;
  transform: translate(-50%, -50%);
  background-color: #333;
  padding: 0 14px;
  border-radius: 50%;
  visibility: hidden;
  opacity: 0;
  transition: 0.5s;
}
.scroll.top {
  visibility: visible;
  opacity: 1;
  transition: 0.5s;
}

main.js


window.addEventListener("scroll", function () {
  const scroll = document.documentElement.scrollTop; //Define the process to get the scroll value from the top in the root element of document with a variable
  const PageTopBtn = document.getElementById("scrollValue");

  if (scroll > 300) {
    document.querySelector(".scroll").classList.add("top");
  } else {
    document.querySelector(".scroll").classList.remove("top");
  }

  PageTopBtn.addEventListener("click", () => {
    window.scrollTo({ //Scroll to a specific combination in the document
      top: 0,
      behavior: "smooth", //Smooth scroll
    });
  });
});


Recommended Posts

Back to top button made only with Javascript (rails, haml)
[Ruby on Rails] Button to return to top
[Rails] Button to return to the top of the page
[How to insert a video in haml with Rails]
I want to push an app made with Rails 6 to GitHub
[With back tricks] How to introduce React to the simplest Rails
Connect to Rails server with iPhone
How to get along with Rails
Introducing React to Rails with react-rails
Timeless search with Rails + JavaScript (jQuery)
How to decorate the radio button of rails6 form_with (helper) with CSS
How to compare only the time with Rails (from what time to what time, something like)
[Rails] How to convert from erb to haml
Convert C language to JavaScript with Emscripten
[Rails] How to use rails console with docker
How to switch thumbnail images with JavaScript
Deploy to heroku with Docker (Rails 6, MySQL)
[Rails] Assigning variables from controller to JavaScript
How to build Rails 6 environment with Docker