How to Add Scroll to Top Button with Progress Bar in JavaScript

Faraz

By Faraz -

Learn step-by-step how to create a Scroll to Top button with a progress bar using HTML, CSS, and JavaScript. Improve site navigation effortlessly.


how-to-add-scroll-to-top-button-with-progress-bar-in-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

A Scroll to Top button helps users navigate easily by allowing them to return to the top of the page with one click. Adding a progress bar makes it even better, as users can see how much they have scrolled. In this tutorial, you will learn how to create a scroll-to-top button with a progress bar using HTML, CSS, and JavaScript.

Prerequisites:

Before starting, make sure you have the following:

  • Basic understanding of HTML, CSS, and JavaScript.
  • A text editor to write your code (e.g., VS Code, Sublime Text).
  • A browser to view and test your project.

Source Code

Step 1 (HTML Code):

First, we’ll create the basic structure for the button and the progress bar. Let's break down the HTML code:

1. HTML Structure

  • <!DOCTYPE html>: Defines the document type as HTML5.
  • <html lang="en">: Starts the HTML document and specifies English as the language.
  • <head> section:
    • Meta tags:
      • charset="UTF-8" ensures proper character encoding.
      • viewport="width=device-width, initial-scale=1.0" makes it mobile-friendly.
    • Title: Sets the page title to "Scroll to Top."
    • Google Fonts: Loads the "Poppins" font.
    • External CSS (styles.css): Links an external stylesheet for styling.

2. Scroll to Top Button (<a> tag)

<a href="#" data-target="html" class="scroll-to-target scroll-to-top">
    <span class="scroll-to-top__wrapper">
      <span class="scroll-to-top__inner" style="width: 0%;"></span>
    </span>
    <span class="scroll-to-top__text"> Go Back Top</span>
</a>
  • This button allows users to scroll to the top when clicked.
  • href="#": Keeps the link functional without redirecting to another page.
  • data-target="html": Used for targeting the <html> element.
  • Classes (scroll-to-target, scroll-to-top) are used for styling and JavaScript interactions.

3. Content Sections

<div class="content-box">
    <h2>Introduction</h2>
    <p>Lorem ipsum dolor sit amet...</p>
</div>
  • Multiple <div> elements with the class content-box contain headings (<h2>) and paragraphs (<p>).
  • These provide enough content for scrolling.

4. External JavaScript and jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="script.js"></script>
  • jQuery (3.7.1) is included to simplify DOM manipulation and animations.
  • External JavaScript (script.js) contains the scroll-to-top functionality.

Step 2 (CSS Code):

Now, let’s style the button and the progress bar using CSS. The button will be fixed to the bottom right of the screen, and the progress bar will animate as the user scrolls. Let’s break it down:

1. Global Styles

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
  • * (Universal Selector): Applies styles to all elements.
  • margin: 0; padding: 0;: Removes default spacing for consistency.
  • box-sizing: border-box;: Ensures padding and border are included in element dimensions.
  • font-family: 'Poppins', sans-serif;: Sets the font for the whole page.

2. Body Styling

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 500vh;
  background-color: #f5f5f5;
  padding-top: 20px;
}
  • display: flex; flex-direction: column; align-items: center;
    • Arranges content in a vertical stack and centers it horizontally.
  • min-height: 500vh;
    • Extends the page height to enable scrolling.
  • background-color: #f5f5f5;
    • Sets a light gray background.
  • padding-top: 20px;
    • Adds spacing at the top.

3. Anchor (<a>) Links Styling

a,
a:hover,
a:focus,
a:visited {
  text-decoration: none;
}

a {
  color: #e8092e;
  transition: all 500ms ease;
}
  • Removes underline (text-decoration: none;) for all link states.
  • Sets link color (#e8092e; - red).
  • Smooth color transition (500ms ease).

4. Scroll-to-Top Button Styling

.scroll-to-top {
  display: flex;
  align-items: center;
  width: auto;
  height: 35px;
  background: transparent;
  position: fixed;
  bottom: 60px;
  right: -12px;
  z-index: 99;
  text-align: center;
  opacity: 0;
  visibility: hidden;
  transform: rotate(-90deg);
  cursor: pointer;
  transition: all 0.2s ease;
}
  • display: flex; align-items: center;: Makes the button content align properly.
  • position: fixed;: Keeps the button fixed on the screen.
  • bottom: 60px; right: -12px;: Places it near the bottom-right.
  • opacity: 0; visibility: hidden;: Initially hides the button.
  • transform: rotate(-90deg);: Rotates the button for a unique look.
  • transition: all 0.2s ease;: Ensures smooth animation effects.

Hover Effect

.scroll-to-top:hover {
  color: #e8092e;
}
  • Changes the text color when hovered.

Show Button on Scroll

.scroll-to-top.show {
  opacity: 1;
  visibility: visible;
  bottom: 70px;
}
  • When .show class is added via JavaScript, the button appears and moves 10px up (bottom: 70px;).

5. Scroll-to-Top Button Inner Elements

.scroll-to-top__text {
  display: inline;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-weight: 700;
  margin-left: 10px;
}
  • Makes the text uppercase, bold, and small (12px).
.scroll-to-top__wrapper {
  display: inline-block;
  width: 30px;
  height: 4px;
  background-color: #e8092e;
  position: relative;
  overflow: hidden;
}
  • A thin (4px) red bar that acts as a progress indicator.
.scroll-to-top__inner {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #171717;
}
  • A black (#171717) overlay that might change dynamically.

6. Content Box Styling

.content-box {
  width: 80%;
  max-width: 800px;
  background: white;
  padding: 20px;
  margin: 20px 0;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}
  • width: 80%; max-width: 800px;: Makes the box responsive.
  • background: white;: White background for readability.
  • padding: 20px; margin: 20px 0;: Adds spacing.
  • box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);: Soft shadow effect.
  • border-radius: 8px;: Slightly rounded corners.

Text Styling Inside Content Boxes

.content-box h2 {
  color: #333;
}

.content-box p {
  color: #555;
  line-height: 1.6;
}
  • Dark gray heading (#333).
  • Slightly lighter paragraph text (#555).
  • Better readability with line-height: 1.6;.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 500vh;
  background-color: #f5f5f5;
  padding-top: 20px;
}

a,
a:hover,
a:focus,
a:visited {
  text-decoration: none;
}

a {
  color: #e8092e;
  transition: all 500ms ease;
}

.scroll-to-top {
  display: flex;
  align-items: center;
  width: auto;
  height: 35px;
  background: transparent;
  position: fixed;
  bottom: 60px;
  right: -12px;
  z-index: 99;
  text-align: center;
  opacity: 0;
  visibility: hidden;
  transform: rotate(-90deg);
  cursor: pointer;
  transition: all 0.2s ease;
}

.scroll-to-top:hover {
  color: #e8092e;
}

.scroll-to-top__text {
  display: inline;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-weight: 700;
  margin-left: 10px;
}

.scroll-to-top__wrapper {
  display: inline-block;
  width: 30px;
  height: 4px;
  background-color: #e8092e;
  position: relative;
  overflow: hidden;
}

.scroll-to-top__inner {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #171717;
}

.scroll-to-top.show {
  opacity: 1;
  visibility: visible;
  bottom: 70px;
}

.content-box {
  width: 80%;
  max-width: 800px;
  background: white;
  padding: 20px;
  margin: 20px 0;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.content-box h2 {
  color: #333;
}

.content-box p {
  color: #555;
  line-height: 1.6;
} 

Step 3 (JavaScript Code):

We now need to write JavaScript to make the button functional. This includes showing the button when the user scrolls down and updating the progress bar as they scroll. Let's break it down step by step.

1. Function: handleScrollbar()

function handleScrollbar() {
  const bodyHeight = $("body").height();
  const scrollPos = $(window).innerHeight() + $(window).scrollTop();
  let percentage = (scrollPos / bodyHeight) * 100;

  if (percentage > 100) {
    percentage = 100;
  }

  $(".scroll-to-top .scroll-to-top__inner").css("width", percentage + "%");
}

What It Does:

  • Calculates Scroll Progress:
    • $("body").height(); → Gets the total height of the page.
    • $(window).innerHeight() + $(window).scrollTop(); → Gets how far the user has scrolled, including the visible part of the screen.
    • (scrollPos / bodyHeight) * 100; → Converts the scroll position into a percentage.
  • Limits the progress bar width to 100%.
  • Updates the width of the .scroll-to-top__inner bar to reflect the scroll progress.

Effect:

  • As you scroll, the progress bar inside the scroll-to-top button grows to show how much of the page is viewed.

2. Function: toggleScrollButton()

function toggleScrollButton() {
  var scrollToTopBtn = $(".scroll-to-top");

  if ($(window).scrollTop() > 100) {
    scrollToTopBtn.addClass("show");
  } else {
    scrollToTopBtn.removeClass("show");
  }
}

What It Does:

  • Checks if the user has scrolled more than 100px.
  • If Yes: Adds the "show" class to .scroll-to-top, making it visible.
  • If No: Removes the "show" class, hiding the button.

Effect:

  • The "Scroll-to-Top" button appears after scrolling down 100px and disappears when at the top.

3. Document Ready Function

$(document).ready(function () {
  handleScrollbar();
  toggleScrollButton();

  $(".scroll-to-top").on("click", function (e) {
    e.preventDefault();
    $("html, body").animate({ scrollTop: 0 }, 800);
  });
});

What It Does:

  • Runs handleScrollbar() and toggleScrollButton() immediately when the page loads to set the correct initial state.
  • Adds Click Event to .scroll-to-top Button:
    • e.preventDefault(); → Prevents default link behavior.
    • Smooth Scroll to Top (animate({ scrollTop: 0 }, 800);)
      • Animates scrolling to the top over 800ms (0.8s).

Effect:

  • The scroll progress bar starts working immediately when the page loads.
  • Clicking the scroll-to-top button smoothly scrolls the page back to the top.

4. Window Scroll Event

$(window).on("scroll", function () {
  handleScrollbar();
  toggleScrollButton();
});

What It Does:

  • Triggers handleScrollbar() and toggleScrollButton() every time the user scrolls.

Effect:

  • The progress bar updates as the user scrolls.
  • The "Scroll-to-Top" button appears/disappears dynamically.
function handleScrollbar() {
  const bodyHeight = $("body").height();
  const scrollPos = $(window).innerHeight() + $(window).scrollTop();
  let percentage = (scrollPos / bodyHeight) * 100;
  if (percentage > 100) {
    percentage = 100;
  }
  $(".scroll-to-top .scroll-to-top__inner").css("width", percentage + "%");
}

function toggleScrollButton() {
  var scrollToTopBtn = $(".scroll-to-top");
  if ($(window).scrollTop() > 100) {
    scrollToTopBtn.addClass("show");
  } else {
    scrollToTopBtn.removeClass("show");
  }
}

$(document).ready(function () {
  handleScrollbar();
  toggleScrollButton();

  $(".scroll-to-top").on("click", function (e) {
    e.preventDefault();
    $("html, body").animate({ scrollTop: 0 }, 800);
  });
});

$(window).on("scroll", function () {
  handleScrollbar();
  toggleScrollButton();
});

Final Output:

how-to-add-scroll-to-top-button-with-progress-bar-in-javascript.gif

Conclusion:

By following this guide, you’ve successfully created a Scroll to Top button with a progress bar using HTML, CSS, and JavaScript. This feature improves the user experience on your website by making navigation easier and more interactive.

With a simple button that shows the scroll progress, users can quickly navigate to the top of the page while keeping track of their scroll position. You can further customize the design, animations, and behavior of the button to match your website's theme.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺