Scroll to the top with JS

Mar 8, 2022
4 min read
713 words

You may have seen various types of website in that there is a button that takes you to the top of the page. Have you ever wondered how it actually works? Well, it's not rocket science or something it's very easy to do and after reading this article I am sure your website will have that button too. So without further due, let's get into it.

Preview

preview

Firstly, We need to create a button. For that in your main page or in the body of your HTML create a button with your suitable icon, for instance arrow-up.

index.html

<button class="scroll-button">
  <img
    src="https://cdn-icons-png.flaticon.com/512/892/892692.png"
    alt="arrow-up"
  />
</button>

Also, you need to make sure that your button is directly inside the body on level one not in the nested divs.

Wrong Place-

index.html

<!--WRONG-->
<body>
  <div>
    <div></div>
    ....
    <!--WRONG Place for button-->
    <button></button>
  </div>
</body>

Correct Place-

index.html

<!--CORRECT-->
<body>
  <div>
    <div></div>
    ....
  </div>
  <!--CORRECT Place for button-->
  <button></button>
</body>

directory

body/
├─ level-one
├─ level-one
├─ level-one/
│  ├─ level-two
│  ├─ level-two/
│  │  ├─ level-three
├─ level-one

The above code explains that how the button should be placed on a level-one.

CSS

Now we've created a button we need to style it. You can style, however you want, but there are many things which you should remember, for that look at the following code-

styles.css

.scroll-button {
  /* position should be fixed so that it sticks to the bottom */
  position: fixed;
  bottom: 5%;
  right: 5%;
 
  /* removing extra syles outline and border */
  outline: none;
  border: none;
  cursor: pointer;
  user-select: none;
  border-radius: 100%; /* making it rounded */
 
  /* Making it's content center */
  display: grid;
  place-items: center;
 
  /* Inital property so that user won't be able to see the button when he visit the page */
  pointer-events: none; /* any event won't work */
  opacity: 0; /* hiding button */
  transition: opacity 500ms ease; /* animation */
  -webkit-tap-highlight-color: transparent; /* removing tap hightlight */
}
 
/* Setting the Image dimensions */
.scroll-button > img {
  width: 50px;
  height: 50px;
}

Javascript

Now we have a button and we've styled it also. Now we just need to make it work so that we can scroll to the top. For that we are going to use Javascript.

script.js

const scrollButton = document.querySelector(".scroll-button");
 
// when the user scroll then show the button otherwise hide it
window.addEventListener("scroll", () => {
  window.pageYOffset > 100
    ? scrollButton.classList.add("show-btn")
    : scrollButton.classList.remove("show-btn");
});
 
// when user click the button take him to the top with smooth behavior
scrollButton.addEventListener("click", () => {
  window.scrollTo({
    top: 0,
    behavior: "smooth", // for smoothly scrolling
  });
});

styles.css

.show-btn {
  opacity: 1 !important;
  pointer-events: all !important;
}

Bonus

Creating a React Component

You can also create a component of this button and place that in your React app. For that you will require the following code.

components/ScrollToTopButton.jsx

// used Technologies : tailwindCSS, React, React-icons
 
import { IoIosArrowUp } from "react-icons/io";
import { useEffect, useState } from "react";
 
export default function ScrollToTopButton() {
  const [showButton, setShowButton] = useState(false);
 
  function scrollEvent() {
    if (window.pageYOffset > 300) {
      setShowButton(true);
    } else {
      setShowButton(false);
    }
  }
  useEffect(() => {
    window.addEventListener("scdddroll", scrollEvent);
    return () => {
      window.removeEventListener("scroll", scrollEvent);
    };
  }, []);
 
  // This function will scroll the window to the top
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth", // for smoothly scrolling
    });
  };
 
  return (
    <>
      {showButton && (
        <button
          onClick={scrollToTop}
          className="fixed bottom-[10%] sm:bottom-[7%] right-0 m-5 sm:m-0 z-50"
        >
          <IoIosArrowUp className="bg-black dark:bg-gray-200 dark:text-darkPrimary text-white rounded-md shadow-lg text-[50px] md:mr-10" />
        </button>
      )}
    </>
  );
}

How to use this Component?

src/App.js

// ..App.js
import ScrollToTopButton from "./components/ScrollToTopButton";
 
function App() {
  return (
    <>
      <main className="container">
        <div></div>
      </main>
      <ScrollToTopButton />
    </>
  );
}
 
export default App;

Wrapping Up

In this article I've covered how you can make a button that scroll the screen to the top automatically. You can also make a button to scroll to the bottom. Now that's your project.

Jatin's Newsletter

I write monthly Tech, Web Development and chrome extension that will improve your productivity. Trust me, I won't spam you.

Share on Social Media: