👨🏻‍💻 Пишем Scroll back кнопку

👨🏻‍💻 Пишем Scroll back кнопку


HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8" />
 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Scroll To Top Button</title>
 <link rel="preconnect" href="https://fonts.googleapis.com" />
 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
 <link
  href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap"
  rel="stylesheet"
 />
 <link
  rel="stylesheet"
  href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,1,0"
 />
 <link rel="stylesheet" href="styles.css" />
</head>
<body class="container">
<nav id="nav" class="container">
 <img src="logo.svg" />
 <div>
  <span class="material-symbols-outlined"> home </span>
  <span class="material-symbols-outlined"> lock </span>
  <span class="material-symbols-outlined"> settings </span>
 </div>
</nav>
<button
 onclick="scrollToTop()"
 id="scroll-top-button"
 class="scroll-top-button"
 type="button"
>
 <span class="material-symbols-outlined"> arrow_upward </span>
</button>
<h2>Lorem ipsum dolor</h2>

<!-- Content goes here -->

<script src="main.js"></script>
</body>
</html>

CSS

body {
 margin: 0;
 padding-top: 72px;
 font-family: Poppins;
}

* {
 box-sizing: border-box;
}

nav {
 position: fixed;
 top: 0;
 left: 0;
 display: flex;
 align-items: center;
 justify-content: space-between;
 height: 72px;
 width: 100%;
 background: #ffffff;
 transition: 0.3s;
}

nav.scrolled {
 box-shadow: 0 10px 20px rgb(0 0 0 / 8%);
}

nav img {
 width: 30px;
 height: 30px;
}

nav div {
 display: flex;
 gap: 12px;
 opacity: 0.7;
}

.container {
 padding-left: 5%;
 padding-right: 5%;
}

.scroll-top-button {
 position: fixed;
 right: 20px;
 bottom: 36px;
 display: grid;
 place-items: center;
 width: 64px;
 height: 64px;
 border: 0;
 border-radius: 50%;
 background: #4285f4;
 color: #f9f9f9;
 cursor: pointer;
 opacity: 0;
 visibility: hidden;
 transition: 0.3s;
}

.scroll-top-button.visible {
 opacity: 1;
 visibility: visible;
}

Javascript

const scrollTopButton = document.querySelector("#scroll-top-button");
const nav = document.querySelector("#nav");

const onScroll = (event) => {
 const scrollPosition = event.target.scrollingElement.scrollTop;

 scrollTopButton.classList.toggle("visible", scrollPosition > 0);
 nav.classList.toggle("scrolled", scrollPosition > 0);
};

const scrollToTop = () => {
 window.scrollTo({ top: 0, behavior: "smooth" });
};

document.addEventListener("scroll", onScroll);


Report Page