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