How can I display different data values on each individual circle counter, rather than all circles showing the same data?

Hey there! I'm trying to get my circular counters to display the counter value that I specify in their class and data-percent. However, currently all four counters are only showing the data from the first counter, even though I've set different data-percent values for each counter in the HTML code. Can anyone help me figure out what's wrong and how to fix it? Any assistance would be greatly appreciated! Below is the provided code for better understanding:

The following code snippet is giving me the displayed result as shown in this picture:

https://i.sstatic.net/efSdd.png

Currently, I'm using this JavaScript code snippet:

<script type="text/javascript>
  (function () {
  var bar, c, percent, r, range;

  percent = $('.pie').data('percent');

  bar = $('.pie').find('.bar');

  r = bar.attr('r');

  c = Math.PI * (r * 2);

  range = (100 - percent) / 100 * c;

  bar.css({
    'stroke-dashoffset': c,
    'stroke-dasharray': c });

  bar.animate({
    strokeDashoffset: range
  }, 1000, 'linear');

  $('.text').prop('Counter', 0).animate({
    Counter: percent
  },
  {
    duration: 1000,
    step: function (now) {
      return $(this).text(Math.ceil(now) + '%');
    }
  });
}).call(this);
</script>

The HTML structure is as follows:

<!--counter new -->
<div class="container-fluid counter"> 
  <div class="row">
    <div class="col-lg-3">
      <div class="svg-box"><span class="text">0%</span>
        <svg class="pie" viewbox="0 0 200 200" data-percent="99">
          <circle r="90" cx="100" cy="100"></circle>
          <circle class="bar" r="90" cx="100" cy="100"></circle>
        </svg>
      </div>
     </div>
     <div class="col-lg-3">
       ...
     </div>
  </div>
</div>
<!--counter new end -->"

The CSS used for styling is displayed below:


.svg-box {
  position: relative;
}

.text {
  position: absolute;
  top: 50%;
  left: 40%;
  transform: translate(-50%, -50%);
  z-index: 1;
  font-size: 3em;
  letter-spacing: 3px;
  font-family: "Raleway", Calibri, sans-serif;
  color: #fff
}

svg {
  transform: rotate(-90deg);
  width: 200px;
  height: 200px;
  background: transparent;
  fill: none;
}
svg circle {
  stroke-width: 1;
  stroke: #999;
}
svg .bar {
  stroke-width: 3;
  stroke: #ffffff;
  stroke-linecap: round;
}

I want the counters to display the value specified in the data-percent attribute that I included in the HTML code. However, all the counters are currently displaying the same value as the first counter. Ideally, I'd like them to display individual data values as shown in this illustration:

https://i.sstatic.net/rANXf.png

Answer №1

I have made some improvements to your code, and I believe it is now functioning correctly.

(function () {

 $('.chart').each(function(){

 let percentage = $(this).data('percentage');
 let bar = $(this).find('.bar');
 let radius = bar.attr('r');
 let circumference = Math.PI * (radius * 2);
 let offset = (100 - percentage) / 100 * circumference;
 bar.css({
  'stroke-dashoffset': circumference,
  'stroke-dasharray': circumference 
 });
 bar.animate({ strokeDashoffset: offset }, 1000, 'linear');

$(this).prev().prop('Counter', 0).animate({ 
    Counter: percentage
  },                                 {
    duration: 1000,
    step: function (current) {
      return $(this).text(Math.ceil(current) + '%');
    }
  });  
 })
}).call(this);

Check out the updated fiddle here: https://jsfiddle.net/xlhp9sq1/

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

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

Is there a way to extract a specific element from an array stored within a form element's value?

I am encountering an issue with retrieving values from an array in an HTML form element using jQuery. Despite my efforts to explain and provide code, I am not getting the desired results. Can someone help me understand what is going wrong in my code? Thank ...

Guide on utilizing jQuery/AJAX data with PassportJS

When I submit a login request using the form fields action="/login", method="post", everything works smoothly. This is similar to the code examples found either here or here. However, when I attempt to send the same information using jquery/ajax, passport ...

What is the best way to rotate a mesh by 90 degrees in ThreeJS?

Currently, I'm working on rotating a mesh by 90 degrees within Three JS. Below is an image illustrating the current position: My goal is to have the selected mesh rotated parallel to the larger mesh. I attempted to rotate the matrix using the follow ...

The proper functioning of border-collapse and empty-cells together is not achieved

Refer to the link provided: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Tables To conceal empty cells, use the rule empty-cells: hide;. This allows a cell's parent element background to shine through the cell if it is emp ...

Change the name of a file to a name chosen by the user while uploading it to an

I'm a beginner when it comes to node.js and I'm facing an issue that I couldn't find a solution for despite looking into various related topics. My problem involves using Node.js on the server side to upload a file and rename it based on a ...

Creating multi-level nested lists with numbering using HTML and CSS

Is there a way to create a unique numbering format using only HTML and CSS lists (<ul> or <ol>)? 1. Item A 2. Item B 3. Item C 3.1. Subitem C.1 3.2. Subitem C.2 3.3. Subitem C.3 4. Item D 4.1. Subitem D.1 4.1.1 Sub-subi ...

The Page is Not Able to Scroll

Occasionally, my app stops allowing scrolling of the entire page length. Everything will be working fine for a while, but then out of nowhere, the page suddenly becomes un-scrollable and you can only interact with the section currently visible on the scree ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

Issue: Module 'xml2json' not found

Encountered an error while running my project package. When I tried to install the necessary packages using npm install xml2json I still encountered another error below. Can anyone provide suggestions or ideas on how to resolve this issue? D:\xa ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Generating a matrix of HTML video elements in p5.js triggers Uncaught TypeError

Struggling to create a 2D array of video objects. It works fine with a regular array, but throws an error when attempting to make it 2D - Uncaught TypeError: Cannot read property 'tv' of undefined. The problem seems to be in this line of code: tv ...

Retrieve data from REST call to populate Material dropdown menu

I am looking to dynamically populate a dropdown menu with data retrieved from a Rest API. I attempted the following code: <Select id="country-helper"> {array.map((element) => ( <MenuItem value={element.code}>{element.country}& ...

CSS: Maintain rounded corners on body border even when scrolling

I am attempting to create a body border on my webpage with rounded corners at the top to simulate the MacOS interface in the browser, similar to the image shown here: https://i.sstatic.net/ECSU9.jpg The issue arises when I scroll, and the top corners van ...

What is the best way to switch the background color of a dropdown div when hovering over it?

I've been working on getting the color to fill the entire dropdown area based on the text you're hovering over, but it's only filling the space around the word. I've set up a Fiddle to demonstrate the issue I'm facing. I'm ne ...

Blending HTML template and WordPress PHP file

I am facing a challenge while attempting to implement a Wordpress template on one of the pages of my website, specifically at http://www.windowblindshadeshutters.com/blog/. The blog has been successfully created, however, I am having trouble preserving our ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

The POST request from the form is returning a null value

I am currently facing an issue with using post in Express and BodyParser to insert data from a form in an EJS file into MySQL. The data keeps returning null, indicating that it is not being parsed correctly from the form to the backend. Can anyone offer as ...