LoginSignup
0
0

More than 3 years have passed since last update.

Javascriptのみで作るトップに戻るボタン(rails,haml)

Last updated at Posted at 2020-10-31

■ はじめに

Javascriptのみで作るトップに戻るボタンについて記事にしました。
この記事で得る内容は以下の通りです。

・Javascriptの基礎知識が増える
・jQueryに依存せず、Javascriptを使ったトップに戻るボタンの作り方が理解できる様になる

・参考にさせて頂いたサイト・動画
JSでscrollしたら◯◯する!スクロールに紐づかせて処理をしましょう!
【脱jQuery】Javascriptのみでトップへ戻るボタンを実装

■ コード

index.html.haml
.scroll#scrollValue
  %i.fas.fa-angle-up

= javascript_pack_tag 'main' -# app/javascript/packs/home/main.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; // documentのルート要素で一番上からのスクロール値を取得する処理を変数で定義
  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({ // 文書内の特定の組み合わせまでスクロールする
      top: 0,
      behavior: "smooth", // スムーススクロール
    });
  });
});
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