The progress bar fails to update once it hits 100%

My circle progress bar is not resetting to start over when it reaches 100%. The code seems to work fine in my browser, but for some reason it's not working on JSFiddle. Here is the link:

https://jsfiddle.net/BrsJsk/5e9hs69y/5/

    window.onload = function() {
  var progressbar = document.querySelector('div[data-progress]'),
    quad1 = document.querySelector('.quad1'),
    quad2 = document.querySelector('.quad2'),
    quad3 = document.querySelector('.quad3'),
    quad4 = document.querySelector('.quad4'),
    counter = document.querySelector('.counter');


  var progInc = setInterval(incrementProg, 1000); // call function every second

  function incrementProg() {
    progress = progressbar.getAttribute('data-progress'); //get current value
    progress++; // increment the progress bar value by 1 with every iteration
    progressbar.setAttribute('data-progress', progress); //set value to attribute
    counter.textContent = 100 - parseInt(progress, 10); // set countdown timer's value
    setPie(progress); // call the paint progress bar function based on progress value
    if (progress == 100) {
      clearInterval(progInc); // clear timer when countdown is complete

    }
  }

  function setPie(progress) {
    /* If progress is less than 25, modify skew angle the first quadrant */
    if (progress <= 25) {
      quad1.setAttribute('style', 'transform: skew(' + progress * (-90 / 25) + 'deg)');
      progressbar.setAttribute('style', 'box-shadow: inset 0px 0px 0px 50px #6edbf2');

    }

    /* Between 25-50, hide 1st quadrant + modify skew angle of 2nd quadrant */
    else if (progress > 25 && progress <= 50) {
      quad1.setAttribute('style', 'transform: skew(-90deg)'); // hides 1st completely
      quad2.setAttribute('style', 'transform: skewY(' + (progress - 25) * (90 / 25) + 'deg)');
      progressbar.setAttribute('style', 'box-shadow: inset 0px 0px 0px 50px #6edbf2');
    }

    /* Between 50-75, hide first 2 quadrants + modify skew angle of 3rd quadrant */
    else if (progress > 50 && progress <= 75) {
      quad1.setAttribute('style', 'transform: skew(-90deg)'); // hides 1st completely
      quad2.setAttribute('style', 'transform: skewY(90deg)'); // hides 2nd completely
      quad3.setAttribute('style', 'transform: skew(' + (progress - 50) * (-90 / 25) + 'deg)');
      progressbar.setAttribute('style', 'box-shadow: inset 0px 0px 0px 50px #6edbf2');
    }

    /* Similar to above for value between 75-100 */
    else if (progress > 75 && progress < 100) {
      quad1.setAttribute('style', 'transform: skew(-90deg)'); // hides 1st completely
      quad2.setAttribute('style', 'transform: skewY(90deg)'); // hides 2nd completely
      quad3.setAttribute('style', 'transform: skew(-90deg)'); // hides 3rd completely
      quad4.setAttribute('style', 'transform: skewY(' + (progress - 75) * (90 / 25) + 'deg)');
      progressbar.setAttribute('style', 'box-shadow: inset 0px 0px 0px 50px #6edbf2');
    }
  }
}
.quad1,
.quad3 {
  transform: skew(0deg);
  /* invisible at -90deg */
}

.quad2,
.quad4 {
  transform: skewY(0deg);
  /* invisible at 90deg */
}


/* Just for demo */

div[data-progress] {
  margin: 40px auto;
}

<div data-progress="0">
  <div class="quad1"></div>
  <div class="quad2"></div>
  <div class="quad3"></div>
  <div class="quad4"></div>
  <div class='counter'>100</div>
</div>

Answer №1

If you want the interval to stop once you reach 100% progress, then you need to reset the progress manually. Follow these steps:

Instead of checking and incrementing the progress value, try this approach:

progress = parseInt(progressbar.getAttribute('data-progress'));
progress = ((progress + 1) % 100);

This means treating the progress as an integer (which it is) and using the modulo operator to bring the progress back to 0 when it reaches 100.

You also must reset all four quadrants of your progress bar. Here's how:

if (progress === 0) {
    quad1.setAttribute('style', 'transform: skew(0deg)');
    quad2.setAttribute('style', 'transform: skewY(0deg)');
    quad3.setAttribute('style', 'transform: skew(0deg)');
    quad4.setAttribute('style', 'transform: skewY(0deg)');
}

Add this code snippet right after updating the progress value. You can remove the lines that clear the interval.

Check out the complete demo below: I've made the interval slightly faster for demonstration purposes.

// JavaScript code goes here
// HTML/CSS code goes here

// Function to increment progress
function incrementProg() {
  // Increment progress logic here
}

// Function to set pie chart visual based on progress
function setPie(progress) {
  // Set pie chart logic here
}
// CSS code goes here
<!-- HTML code goes here -->

Answer №2

If you want to reset your pie chart, you can create an init function and then clear the interval using clearInterval(progInc).

  function initializePie() {
        quad1.setAttribute('style', 'transform: skew(0deg)');
            quad2.setAttribute('style', 'transform: skewY(0deg)');
            quad3.setAttribute('style', 'transform: skew(0deg)');
            quad4.setAttribute('style', 'transform: skewY(0deg)');
      progress = progressbar.setAttribute('data-progress', '-1');
      progInc = setInterval(incrementProg, 100);
  }

Visit this link for reference

Answer №3

In order to reset the process, you must ensure that when the progress reaches 100, set it back to 0 without clearing the interval. After that, revert the style back to its initial state.

For example, see this working demo https://jsfiddle.net/72n4mjLa/:

if (progress == 100) {
    progressBar.setAttribute('data-progress', 0);
    box1.setAttribute('style', 'transform: skew(0)');
    box2.setAttribute('style', 'transform: skew(0)');
    box3.setAttribute('style', 'transform: skew(0)');
}

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

Blocking server.js in node.js can be achieved by modifying the code to prevent

Challenge Description In my server.js file, I have included a config file. This is how my server.js file looks: Includes some necessary imports Requires config.js -> makes an API call to get the configuration data using promises Starts the ser ...

When attempting to open a popup form by clicking a button, the code fails to function on IE6

Everything seems to be running smoothly on Firefox, however I am encountering issues with Internet Explorer 6. Here is a snippet of the problematic code: document.getElementById('layout').style.opacity = .7 document.getElementById('layout&a ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

exchanging a library for a different one

I'm faced with a relatively simple task here, but as I am just beginning to delve into object-oriented programming, it is proving to be quite perplexing for me. Currently, I am using the lon_lat_to_cartesian function from the following source: functi ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

Open the PDF document in a stylish jQuery popup like fancybox or a similar plugin

Can a PDF file be loaded in a popup? I understand that some browsers may require Adobe Reader to view PDFs, but Chrome has its own built-in PDF viewer. ...

Customize checkbox and label using jQuery

I have a scenario where I have multiple checkboxes and corresponding labels. When the answer is correct, I want to change the background color of the selected checkbox and label. <input type="checkbox" id="a" class="check-with-label" /> <label fo ...

Having trouble transferring sound files to Cloudinary API through javascript

I have successfully implemented a function in my React Native application to upload images to Cloudinary. Now, I am trying to modify the function to upload audio files as well. Despite specifying the "resource_type" parameter as "raw", "video", or "auto", ...

Issue with Closing Bootstrap 4 Modal on Hide Operation

I had successfully implemented this feature in bootstrap 3, but unfortunately, I have not been able to replicate the same in bootstrap 4 (beta). The modal for the sign-in form is structured as follows: <div class="modal fade" id="signInModal" tabindex ...

The NativeAppEventEmitter does not return any value

I've been grappling with obtaining a logged in user access token for quite some time. I initially faced challenges with it in JavaScript, so I switched to Objective-C and managed to succeed. Following that, I referred to this RN guide: https://facebo ...

How can I dynamically assign a className in a React component based on the current state when importing styles?

I've been utilizing the style-loader to insert CSS modularly into my components ({style.exampleClassName}). My goal is to showcase a loader for a specific duration before displaying an image (at least 16 of these components in a grid layout). This i ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

What is the best way to stop vertically aligned elements from overlapping the navbar in Bootstrap 4?

I have successfully aligned my content vertically, but I encountered an issue when resizing the browser window vertically - the aligned content overlaps with the navbar. What I want is for the vertically aligned content to stop at the navbar. I have exper ...

Looking for assistance with HTML/CSS code

Adding the code snippet below into my Shopify product-liquid file caused chaos on the page, altering the font and even changing the shape of the add to cart button... The problematic code is shown below: <div id="shopify-section-product-icon-gallery" ...

Sleek carousel design with optimal spacing between images

Solving the Issue Utilizing Ken Wheeler's Slick plugin has allowed me to create a carousel on my website. However, I've encountered an issue where the images inside the <a> tag aren't evenly spaced and are even overlapping in some ins ...

Having trouble with RethinkDB filter not returning any matches?

Encountering an obstacle with RethinkDB while using NodeJS. Attempting to utilize a basic .filter() function, but for some mysterious reason, it fails to retrieve a result. The current code snippet in question looks like this: const someID = 1234; ...