Monitor the scrolling progress across four separate HTML pages without the percentage decreasing when scrolling back up

I am in the process of developing an e-learning platform and I would like to include a scrolling indicator that visually represents the progress of pages read. The website consists of four HTML pages, with each page corresponding to 25% of the scroll bar. Ideally, when all four pages have been scrolled through, the indicator should reach 100%. I have attempted to implement the following code which successfully allocates 25% for one HTML page. However, when I scroll back up, the percentage decreases again. What I really want is for the indicator to stay at 25% once the page has been fully scrolled. Despite my efforts as a programming beginner and numerous searches on Google, I have not been able to find a solution. Any help would be greatly appreciated.

One possibility I considered was using an if-else statement, so I experimented with variations by adjusting variables, numbers, and their order but nothing seemed to work:

if (scrolled === 25) {document.getElementById("myBar-fotografie").style.width = 25 + "%"; }
else {document.getElementById("myBar-fotografie").style.width = scrolled 
+ "%";}

So far, I have only focused on maintaining the indicator at 25% after full scrolling of a single page, without incorporating the percentages from all four HTML pages. Figuring out how to combine them is currently beyond my knowledge level.

<html>
<p> Fotografie </p>
<div class="progress-container">
<div class="progress-bar" id="myBar-fotografie"></div>
</div>
// "Fotografie" signifies the headline for the four subpages
</html>


<style>
.progress-container {
width: 100%;
height: 8px;
background: #ccc;
}

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


<script>
// Addition of a script that triggers function when user scrolls
window.onscroll = function() {myFunction()};

function myFunction() {
var winScroll = document.body.scrollTop || 
document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - 
document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 25;

document.getElementById("myBar-fotografie").style.width = scrolled + "%";
} 
</script>

Answer №1

While waiting, make sure to create a functional code Here's an example of a progress bar at 25%

const ProgressBar = function () {
  let position = document.documentElement.scrollTop;

  window.addEventListener('scroll', () => {
    let scrolls = document.documentElement.scrollTop;
    let ws = window.pageYOffset, wh = window.innerHeight, dh = document.body.clientHeight;
    let scrollPercent = (ws / (dh - wh)) * 25;

    if (scrolls > position) {
      const progressBar = document.querySelector('#progress');
      if (ws > 50) {
        progressBar.setAttribute('style', 'width:' + scrollPercent + '%');
      } else {
        progressBar.removeAttribute('style');
      }
    }

    position = scrolls;
  });
}();
.container {
  width: 100%;
  margin: 0 auto;
}

.bar {
  position: fixed;
  background: rgb(255, 0, 0);
  height: 10px;
  width: 0;
  top: 0;
}

h1 {
  text-transform: uppercase;
  margin: 20px 0;
}

h1 span {
  color: rgb(60, 177, 6);
}

p {
  margin-bottom: 10px;
}
<div id="progress" class="bar"></div>
  <div class="container">
    <h1>proggres bar test - <span>scroll</span></h1>
    <div class="lipsum">
      <p>
       [Text has been shortened for brevity]
      </p>

     [Remaining content truncated due to length]
    </div>
  </div>

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

Angular - Loading images on demand

I've recently started learning Angular and Typescript, and I've run into an issue that I could use some help with. I want to implement lazy loading for all the images in my application by adding the loading="lazy" attribute to each < ...

Encountering an error while attempting to map a collection in React JS - the value is

Within my state, I have a collection set up like this: getInitialState: function() { return { studentId: 666, activeTabId: 1, sections: [ {name: 'were', value: 1, label: 'Basic Details'}, {na ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Adding a fresh, spacious breakpoint in Bootstrap 4 with just CSS

I encountered an issue when the extra large Bootsrap 4 max container width, set at 1140px, was not wide enough for my needs. I aim to ensure that my websites look good on large monitors as well, but the bootstrap grid is too narrow. The most straightforwar ...

The importance of CSS z-index in optimizing for mobile responsiveness

In my jquery modal dialog box, I wanted to create a shadow effect only between the dialog box and the screen. To achieve this, I added an overlay using a <div>: <div id="overlay" class="overlay btn-hidden"></div> <d ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

What is the solution for the issue of encountering an undefined key array email while attempting to log in through the form?

I encountered an issue while working on a login form that communicates with the database using PHP at the backend. Even though I have verified the correctness of my login credentials, I am facing an error related to undefined array keys 'email and pas ...

Challenges with the grid layout on a responsive Wordpress portfolio site

I've encountered an issue with a Wordpress theme, as the portfolio grid doesn't appear to be extending fully across the page. You can observe the problem after the 'crashes' image box at this link - Any assistance in resolving this ma ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

Manage the sequence in which the various paths of an SVG element are displayed

Searching for a way to display an image in HTML with a rounded dashed border? Take a look at the example below: https://i.sstatic.net/YrCZS.png The number of dashes and their colors can be controlled, similar to what you see in WhatsApp's status tab ...

Using `getJson` to parse the tree structure

I am currently working with a JSON file that contains order data. The structure of the JSON file is as follows: { "orders": [ {"name": "Peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140110011624050b0 ...

Is it possible to customize the background color for particular days in FullCalendar?

How can I set background colors for specific days? While experimenting, I discovered this method: $('.fc-day15').css('backgroundColor','black'); The only issue is that the colors appear on the 16th day in the calendar grid, ...

Can you provide me with instructions on utilizing PNGs to create edge masks for an image?

After experimenting with border-image and PNGs to achieve textured borders, I'm curious if there is a method for masking in a similar fashion? I recently came across the Rumchata website which showcases what I have in mind. Their background has a blu ...

Having trouble transferring data from an aspx file to the code behind using $.ajax({ type: "POST", with Visual Studio 2017 C#?

Utilizing web-forms to gather data from a form and then transmit the data to the code-behind in order to forward it to an API. By clicking on a button, I trigger a JavaScript function that gathers the data and then sends it over to my aspx.cs file for comm ...

Ensuring all ajax calls have completed before proceeding using selenium webdriverjs

In my attempt to create a function that can wait for all active (jQuery) ajax calls to complete in a Selenium WebdriverJS test environment, I am faced with challenges. My current approach involves integrating the following components: Implementing WebDri ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

Is jQuery the solution for tidying up messy HTML code?

Is there a way to clean up this markup using jQuery? <span style="font-size:19px"> <span style="font-size:20px"> <span style="font-size:21px"> Something </span> </span> </span> I'm looking to tra ...

A guide on iterating through a multi-dimensional array in Javascript and organizing the results in a specified sequence

Updated on 18th January, 2021 (refer to bold changes) I'm currently facing difficulties while attempting to iterate through a nested array and then organize the output in a specific order. Can you assist me in finding a solution to make this work or ...

Tips on inline password field placement for a better user interface experience?

While creating a registration form, I ran into a user interface problem. There are two specific changes I'd like to make: The label for Confirm Password should be inline on the same line. The password input should have an eye icon embedded within it ...