Display a progress bar that shows completion based on the maximum value supplied

I successfully created a progress bar using HTML, CSS, and Javascript. It functions perfectly up to a provided value of 100. However, if a value higher than 100 is given, the progress completes but the value continues to change until it reaches the maximum value.

Expectation: I expect the progress to be completed based on the provided value only.

Here is the code I used:

window.addEventListener("load", function
(event){
  let circle = document.querySelectorAll('.circle');
  console.log(circle);
  circle.forEach(function(progress){
    let degree = 0;
    let percentage=0;
    var targetDegree = parseInt(progress.getAttribute('data-degree'));
      let color = progress.getAttribute('data-color');
      let number = progress.querySelectorAll('.number');
      let childNumber = progress.querySelectorAll('.totalfilling');
      var interval = setInterval(function(){
        degree+=1;
        if(degree > targetDegree){
          clearInterval(interval);
          return;
        }
        if(targetDegree > 100){
            percentage = targetDegree / degree;
            console.log(percentage);
        }
        progress.style.background = `conic-gradient(
        ${color} ${degree}%, #222 0%)`;
        number[0].innerHTML = degree;
        console.log(degree);
        number[0].style.color =  color;
        childNumber[0].innerHTML = '<h5>'+targetDegree+'</h5>'
      }, 50)
  });
});
*
{
  margin:0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.container{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}
.container .circle{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
.container .circle::before{
  content: '';
  position:absolute;
  inset: 5px;
  border-radius: 50%;
  background: #222;
  opacity: 0.8;
}
.container .circle::after{
  content: '';
  position:absolute;
  width:120px;
  height: 120px;
  border-radius: 50%;
  background: #fff;
  border: 15px solid #4d4c51;
  box-shadow: inset 0 5px 10px rgba(0,0,0,0.25),
  0 10px 10px rgba(0,0,0,0.75),
  0 -2px 2px rgba(255,255,255,0.5),
  inset 0 4px 2px rgba(0,0,0,0.25),
  inset 0 -2px 2px rgba(255,255,255,0.5);
}
.container .circle .number{
  position:relative;
  color: #fff;
  z-index: 10;
  line-height: 1em;
  font-size: 2em;
}
.container .circle .number span{
  font-size: 0.5em;
  font-weight: 500;
}
.container .circle h4{
  position:relative;
  color: #0b60e9;
  z-index: 10;
  font-weight: 500;
  font-size: 0.8em;
  line-height: 0.6em;
}
.countperhour{
    margin-left:40px;
    font-size:18px;
}
.totalfilling{
    margin-top:10px;
    color: black;
  z-index: 10;
  font-weight: 500;
  font-size: 18px;
  line-height: 0.6em;
}
 <div class="App">
      <div class="container">
        <div class="circle" data-degree="200" data-color="#0b60e9">
        <div class="countperhour">
         <h4>C/h</h4>
         </div>
          <h2 class="number"></h2>
          <div class="totalfilling">
            <h5>1000</h5>
          </div>
        </div>
      </div>

Please review the code above and provide your suggestions.

Answer №1

It is important to make adjustments to both your percentage and condition for stopping the interval and count. Additionally, avoid using querySelectorAll in this scenario

window.addEventListener("load", function
(event){
  let circle = document.querySelectorAll('.circle');
  console.log(circle);
  circle.forEach(function(progress){
    let degree = 0;
    let percentage=0;
    var targetDegree = parseInt(progress.getAttribute('data-degree'));
      let color = progress.getAttribute('data-color');
      let number = progress.querySelector('.number');
      let childNumber = progress.querySelector('.totalfilling');
      var interval = setInterval(function(){
        degree+=1;
        if(percentage >= 1){
          clearInterval(interval);
          return;
        }
        percentage = degree/targetDegree ;
        progress.style.background = `conic-gradient(
        ${color} ${percentage*100}%, #222 0%)`;
        number.innerHTML = degree;
        console.log(degree);
        number.style.color =  color;
        childNumber.innerHTML = '<h5>'+targetDegree+'</h5>'
      }, 50)
  });
});
*
{
  margin:0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.container{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}
.container .circle{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
.container .circle::before{
  content: '';
  position:absolute;
  inset: 5px;
  border-radius: 50%;
  background: #222;
  opacity: 0.8;
}
.container .circle::after{
  content: '';
  position:absolute;
  width:120px;
  height: 120px;
  border-radius: 50%;
  background: #fff;
  border: 15px solid #4d4c51;
  box-shadow: inset 0 5px 10px rgba(0,0,0,0.25),
  0 10px 10px rgba(0,0,0,0.75),
  0 -2px 2px rgba(255,255,255,0.5),
  inset 0 4px 2px rgba(0,0,0,0.25),
  inset 0 -2px 2px rgba(255,255,255,0.5);
}
.container .circle .number{
  position:relative;
  color: #fff;
  z-index: 10;
  line-height: 1em;
  font-size: 2em;
}
.container .circle .number span{
  font-size: 0.5em;
  font-weight: 500;
}
.container .circle h4{
  position:relative;
  color: #0b60e9;
  z-index: 10;
  font-weight: 500;
  font-size: 0.8em;
  line-height: 0.6em;
}
.countperhour{
    margin-left:40px;
    font-size:18px;
}
.totalfilling{
    margin-top:10px;
    color: black;
  z-index: 10;
  font-weight: 500;
  font-size: 18px;
  line-height: 0.6em;
}
    <div class="App">
        <div class="container">
            <div class="circle" data-degree="200" data-color="#0b60e9">
                <div class="countperhour">
                    <h4>C/h</h4>
                </div>
                <h2 class="number"></h2>
                <div class="totalfilling">
                    <h5>1000</h5>
                </div>
            </div>
        </div>
    </div>

Consider the presence of only one element.

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

Searching Text Boxes with Javascript: A Better Way to Handle Arrays

I'm struggling to implement a feature where users can search for authors in a database and be redirected to the corresponding HTML if found. Otherwise, it should display a message saying "No Author Found"... I need some assistance in getting this fun ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

How to integrate external JavaScript files with Angular CLI and Webpack

I'm facing a challenge on how to incorporate JS files (vendors) after transitioning Angular Cli from SystemJs to Webpack. For instance Option A I have npm-installed js files. Simply adding script tags to the head tag doesn't work, and it doesn ...

Create a timer that plays music when a button is pressed

My goal is to initiate a timer when a specific button is clicked. While there are many timers available that start upon page load, I have not been able to find one that begins upon clicking a button. Additionally, the timer must start at the same time as ...

Incorporating an else statement into a function that handles AJAX calls upon receiving a response

My code is almost perfect, but there's just one issue. Whenever an invalid email is entered, the else statement in the PHP response makes it look like the form was still successful. How can I modify my current code to display the appropriate error mes ...

Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV. This is the sn ...

Creating a balanced height for child elements using CSS

If you are looking to display a list of colors with each color occupying an equal fraction of the height, here is how you can achieve it. Imagine presenting four colors in a list with a fixed height and a thick border around it: The example shown above is ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

The radio button default selection is checked, but the desired styles are not being applied

My webpage features two radio buttons, "No" and "Yes," with the default selection being "No." I have implemented CSS styles for the checked elements, but they only work once physically selected. My goal is to apply these styles immediately on page load wit ...

After setting up a Mongoose schema for authentication, how can I effectively perform database queries with MongoDB?

After successfully setting up authentication for my node.js (Express) app using Passport-local and Mongoose schema, I organized the folder structure as follows: app - app.js - config - auth.js - keys.js - passport.js - models - User.js - ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Exploring the wonders of ExpressJS session variables

Having transitioned from a PHP background to focusing on JS, I find myself adjusting to the differences in handling session variables. In PHP, the $_SESSION global variable was very convenient as it allowed easy access to session data throughout the code. ...

What steps can I take to resolve this CSS problem?

I'm trying to create a box around specific html elements, but the current code is causing each element to be enclosed individually. I don't want to use the html or body element as I have other elements that need to remain outside of the box. h1, ...

Tips for aligning 2 columns perfectly in a 3 column layout

I am facing an issue with a grid section where the grid-template-column is set for 3 columns, but sometimes the content loaded dynamically only fills 2 columns. I am attempting to center the columns when there are only 2. Despite going through the grid CS ...

When a client sends a GET request to the server, an error occurs due to the absence of 'Access-Control-Allow-Origin' header in

I am encountering an issue with my node/express js application running on localhost while making a 'GET' request to Instagram's api. The error message I keep receiving is: XMLHttpRequest cannot load https://api.instagram.com/oauth/authorize ...

Utilize the split() function to break down a string into separate

I'm facing an issue with splitting a string into an array using a regex that doesn't seem to be working properly. Here is my code: <script type="text/javascript"> function GetURLParameter(sParam) { var sPageURL = window.l ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

Tips for Implementing a "Please Hold On" Progress Bar in ASP.NET

I have a master page named siteMaster.master, an aspx page called submission.aspx, and a user control named attachment.ascx. The script manager is included in my master page. The submission page inherits the master page and registers the user control attac ...