code for tracking progress bar on a div using a scroll event listener in vanilla JavaScript

I am currently working on a vertical "progress bar" that will serve as a timeline element. However, I am facing the issue of making it match the height of a specific div rather than the body itself.

Despite numerous attempts, I have yet to find a solution, and I prefer not to share my unsuccessful methods to prevent confusion.

Below is the code that successfully adjusts the bar according to the body's height. I would greatly appreciate any assistance or advice on modifying this code to reflect the height of an individual element:

function adjustHeight() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var totalHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolledPercentage = (winScroll / totalHeight) * 100;
  document.querySelector(".progress_bar").style.height = scrolledPercentage + "%";
}
window.addEventListener('scroll', adjustHeight);

Answer №1

const scrollableDiv = document.querySelector('.a');
function updateProgressBar() {
  const heightDifference = scrollableDiv.scrollHeight - scrollableDiv.clientHeight;
  const scrolledPercent = (scrollableDiv.scrollTop / heightDifference) * 100;
  document.querySelector(".p_bar").style.width = `${scrolledPercent}%`;
}
scrollableDiv.addEventListener('scroll', updateProgressBar);
.a{
  height:100vh;
  overflow:scroll;
  color:#fff;
}
.content{
  height:300vh;
  width:100%;
  background: #444;
}

.p_bar{
  width:1%;
  height:20px;
  background: dodgerblue;
  position:sticky;
  top:20px;
  border-radius:20px;
  
}
<html>
  <body>
  
    <div class="a">
      <div class="content">
        <h1>please scroll </h1>
        height/width
        
        <div class="p_bar"></div>
      </div>
    </div>
    
  </body>
</html>

If this solution doesn't work for you, feel free to leave a comment and I'll do my best to assist. Thank you.

Answer №2

Finally presenting the code with the progress bar functionality! The width of the progress bar increases only after the user scrolls past the red div and stops at 100% once they scroll beyond the content div.

// Trigger myFunction when the page is scrolled
window.onscroll = function() {myFunction()};

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
 
  const contentHeight  =  document.querySelector(".content").offsetHeight
  const contentOffssetTop =  document.querySelector(".content").offsetTop
  
  var scrolled = (winScroll / height) * 100;
  let ScrollBarWidth
  const diff=  winScroll - contentOffssetTop
  if(diff <= 0){
     ScrollBarWidth=0
  }else{
     //check if we hav reached div bottom 
     if( (winScroll +100) <= (contentOffssetTop + contentHeight)  ){
          ScrollBarWidth=(diff /contentHeight)*100
     }else{
          ScrollBarWidth=100
     }
  }
  document.getElementById("myBar").style.width = ScrollBarWidth + "%";
}
body {
  margin: 0;
  font-size: 28px;
  font-family: Arial, Helvetica, sans-serif;
}

.header {
  position: fixed;
  top: 0;
  z-index: 1;
  padding:1rem;
  width: 100%;
  background-color: #f1f1f1;
}

.progress-container {
  width: 100%;
   background-color:"red";
  height: 8px;
  background: #ccc;
}

.progress-bar {
  height: 8px;
  background: #4caf50;
  width: 0%;
}

.content {
  padding: 100px 0;
  margin: 50px auto 0 auto;
  width: 80%;
}

.offsset {
  background-color: red ;
  height: 700px;
  width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
 <div class="offsset">ofsset div</div>
<div class="header">
  <h2>Scroll Indicator</h2>
  <div class="progress-container">
    <div class="progress-bar" id="myBar"></div>
  </div>  
</div>

<div class="content">
  <h3>Scroll Down to See The Effect</h3>
  <p>We have created a "progress bar" to <b>show how far a page has been scrolled</b>.</p>
  <p>It also <b>works when you scroll back up</b>.</p>
  <p>It is even <b>responsive</b>! Resize the browser window to see the effect.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit... 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to convert the instructions or code meant for webpack.config.js so that they can be applied to the vue.config.js file?

Having encountered an issue with vue-cli, I found out that instead of webpack.config.js, it uses a vue.config.js: const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, }) After ins ...

Update a Div automatically without causing it to scroll back to the beginning of the Div

I'm encountering an issue with a script on my website that refreshes a Div every 20 seconds. The problem is, after the refresh, it automatically scrolls to the top of the Div. I want it to remain at the last scroll position and not jump to the top. Ca ...

I have successfully configured the div to show only one at a time, however, I am currently facing an issue with turning off the div

My goal is to disable all annotations within a specific div class and then enable just one particular ID afterwards. This method is meant to ensure that only one annotation can be open at any given time. However, I have encountered an issue with the Javasc ...

Discover how to determine the direction of a div element when utilizing the dir="auto" attribute in HTML5 with JavaScript

I'm experiencing an issue with a div that has the dir attribute set to auto. My goal is to retrieve the rendered direction using javascript After attempting div.dir, I only receive the 'auto' value. Is there a method available to detect if ...

Using an external file to control the Angular $md-dialog

I have encountered a small issue while using md-dialog from Material Design that is causing me some trouble. The dialog serves as a form for creating a new record in the database, and I need its controller to be loaded from an external file. This is becau ...

Strategies for selecting glyphs in SVG fonts based on their Unicode properties

My goal is to extract specific characters from SVG fonts created for music engraving. Music fonts typically include a large collection of characters (> 3500), but I only require a small subset of them for caching glyphs in compressed form to ensure quic ...

Issue with JSViews visible link and converter not functioning properly

After updating to the latest version of JsViews, I encountered a problem. When using a data-link like "visible{:property}", everything works fine. However, when using a data-link like "visible{convert:property}", it does not work as expected. It appears ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

retrieving information within an ajax function's callback

I'm currently facing an issue with passing data from an ajax function to my main app. It seems that I cannot successfully pass the data outside of the function. Despite reading through various suggestions from other similar questions, nothing seems to ...

Using Backbone.js to Persist Information on the Server

Currently, I'm in the process of integrating my Backbone.js application with the server. One thing to mention is that I have customized my sync function in the collection to utilize jsonp: window.Project = Backbone.Model.extend({ initialize:func ...

Exploring HTML5 Canvas 2D Frameworks with an emphasis on collision detection and physics simulations

I am seeking the optimal strategy for managing objects within the canvas context. My initial project involves the following tasks: Create a ground drawing. Release a circle onto the ground with collision detection and elasticity. Trigger an explosion tha ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

Challenge with AngularJS 1.6.8: Struggling to transfer data effectively between controller and view

I seem to be lost in my code. Here are the code snippets for all the respective files. It's a simple Single Page Application with routing. index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="utf ...

Javascript Promise: managing the flow of execution

There are a series of tasks that I need to accomplish using an API. It's crucial that these functions are executed sequentially. Each of the functions mentioned below returns a valid promise. a(analyticsConfig._listConfig) .then(function() { ...

Issue with moment library causing date to appear incorrect on 31st day

I am experiencing an issue when finding the difference between 2 dates in years. Specifically, when I choose the 31st date, it returns an invalid result as NaN. However, with other dates, the calculation displays the correct outcome. const selectedValu ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

Importing dynamic NodeJS modules from one module

ModuleA src index.js modules utility.js ModuleB src framework activities activity.js ModuleA serves as the main "runnable" module in this setup, while ModuleB acts as a framework li ...