Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage :

var percentage = Math.round(sum * 100 / total);

Next, I place this value here :

<div class="pie animated" id="pie-get-percentage"></div>

$('#pie-get-percentage').html(percentage);

SVG

$(document).ready(function() {
    $('#pie-get-percentage').html(percentage);

    function $$(selector, context) {
        context = context || document;
        var elements = context.querySelectorAll(selector);
        return Array.prototype.slice.call(elements);
    }

    $$('.pie').forEach(function(pie) {
        var p = parseFloat(pie.textContent);
        var NS = "http://www.w3.org/2000/svg";
        var svg = document.createElementNS(NS, "svg");
        var circle = document.createElementNS(NS, "circle");
        var title = document.createElementNS(NS, "title");

        circle.setAttribute("r", 16);
        circle.setAttribute("cx", 16);
        circle.setAttribute("cy", 16);
        circle.setAttribute("stroke-dasharray", p + " 100");

        svg.setAttribute("viewBox", "0 0 32 32");
        title.textContent = pie.textContent;
        pie.textContent = '';
        svg.appendChild(title);
        svg.appendChild(circle);
        pie.appendChild(svg);
    });

});

CSS

.pie-wrapper {
    .pie {
        width: 100px;
        height: 100px;
        display: inline-block;
        margin: 10px;
        transform: rotate(-90deg);
    }
    svg {
        background: $primary;
        border-radius: 50%;
    }
    circle {
        fill: $primary;
        stroke: $secondary;
        stroke-width: 32;
    }
    @keyframes grow {
        to {
            stroke-dasharray: 100 100
        }
    }
    .pie.animated {
        animation: grow 2s linear;
    }
}

I previously believed that adjusting the .pie.animated CSS properties would allow me to animate up to the dynamic value, but so far, only the full circle has been animated.

Essentially, if my value is 42%, I aim to expand my circle to reflect 42% of the SVG. However, my challenge lies in applying a dynamic value to the CSS animation. It is possible that using inline CSS might be necessary, but I am uncertain if it can be utilized for animation keyframes.

The JSFiddle link is available here

Answer №1

After experimenting with the JQuery portion of your JSFiddle, here is what I came up with.

<div class="pie">60%</div>

<div class="pie">90%</div>

<div class="pie">12%</div>

The concept is straightforward—I utilized a JavaScript interval timer to invoke the count function repeatedly. Additionally, I introduced variables such as max-val, inc-val, and others to facilitate its functionality.

function $$(selector, context) {
    context = context || document;
    var elements = context.querySelectorAll(selector);
    return Array.prototype.slice.call(elements);
} 

function count(){
    var isUsed = false;
 $$('.pie').forEach(function(pie) {
    var p = parseFloat(pie.textContent);

    if(pie.maxValue == null){
         pie.maxValue = p;
         pie.incValue = p / 100.0;
         pie.lastValue = 0;
    }
    else
        pie.lastValue = pie.lastValue + pie.incValue;

   if(pie.lastValue <= pie.maxValue){
        var NS = "http://www.w3.org/2000/svg";
        var svg = document.createElementNS(NS, "svg");
        var circle = document.createElementNS(NS, "circle");
        var title = document.createElementNS(NS, "title");

        circle.setAttribute("r", 16);
        circle.setAttribute("cx", 16);
        circle.setAttribute("cy", 16);
        circle.setAttribute("stroke-dasharray", pie.lastValue + " 100");

        svg.setAttribute("viewBox", "0 0 32 32");
        title.textContent = pie.textContent;
        pie.textContent = '';
        svg.appendChild(title);
        svg.appendChild(circle);
        pie.appendChild(svg);

       isUsed = true;
   }

});
    if(isUsed)
        window.setTimeout(function() {  count(); }, 30);
}

window.setTimeout(function() {  count(); }, 30);

count();

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

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

What method can I use to update the content of a textbox using JQuery?

Currently, I have a script in place that successfully alters the value of my textbox as needed. However, I am looking for ways to enhance this functionality even further. var total = 0; // adds a decimal and 2 zeros $('input:checkbox:checked').e ...

Utilize Postman to send a JSON body in a POST request to trigger a stored procedure on Microsoft SQL Server

I need to send a JSON request using the Postman app, utilizing the POST method to retrieve data. My boss, who is overseeing my training, assigned me this task. I've scoured the web for a week but haven't found a solution yet. Initially, I sugges ...

Icons from Material Design Lite are not appearing as expected when integrated into an Angular project

Recently, I integrated MDL into my Angular project. While most of it is functioning properly, the MDL icons seem to be giving me trouble... I've implemented them using <i class="material-icons">share</i>, but instead of displaying as an i ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Email sending through PHP AJAX can be done without refreshing the page. The email action is handled in email.php and incorporated into

I am having trouble sending this with AJAX. The error message I keep getting is: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more assistance, please visit @ jquer ...

Creating eight equal sections within HTML <div> elements using Bootstrap

I am brand new to Angular. I need to design something like this: https://i.sstatic.net/Zcb9i.png However, I'm struggling to find the right solution. Here is what I have so far: https://i.sstatic.net/7hsrk.png. Having been a backend developer, I&ap ...

What is the method to apply custom styles (CSS) to individual options within a jQuery UI selectmenu?

When working with an HTML form that includes a select element, I encountered a design challenge. <select id='myselect'> <option value='1'>1</option> <option value='2'>2</option> ... <option va ...

Ways to display sneak peeks of preceding and succeeding images within a carousel using Bootstrap 5

I am looking to achieve a carousel effect where the previous and next images partially show on either side of the central image, similar to what is shown in this example: https://i.sstatic.net/HahbP.png Below is the code snippet. <div class="c ...

Scrolling jqgrid to focus on the current day column and implementing a blinking effect on cells with stored data

I have a jqgrid with 38 columns of data, where the first 6 columns are frozen and the rest are unfrozen. Depending on the combo box selection, it shows either dates or months (see sample image here). After loading the grid, I want it to automatically scrol ...

What is causing the issue with the code `exports = { z: function() {} };` not functioning as intended?

Script A exports = { z: function() { console.log('aZ'); } }; Script Main require('./a').z(); // error Have you ever wondered why require('./a') ends up returning an empty object? ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

unable to navigate to next or previous page in react-bootstrap-table2-paginator

I successfully implemented a table with pagination using react-bootstrap-table2-paginator. On each page number click, it calls an API to fetch the table data. However, I encountered issues with the next page, previous page, and last page buttons not workin ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

jQuery Validate SubmitHandler not triggering when processing Ajax submission

When I try to submit my form in the view to the controller using ajax, here's what I have: @section scripts{ @Scripts.Render("~/bundles/jqueryval") <script> $(document).ready(function() { // Mask $("#Te ...

What is the correct method to include basic authentication headers in a post request for retrieving HTML content?

One of the projects I'm currently working on involves a POST endpoint that is protected by basic auth and returns an HTML form. This particular endpoint is hosted using an express server and secured with passport's basic auth. My goal is to creat ...

When interacting with the iframe in an Ionic3 app, it suddenly crashes

Greetings! I have integrated a flipping book URL inside an iframe: <ng-container> <iframe [src]="eUrl" id="flipping_book_iframe" frameborder="0" allowfullscreen="allowfullsc ...

I'm having trouble getting ddft.js to function correctly as demonstrated in the examples

Looking to enhance a web page table with drop-down filters on the columns? Check out ddtf.js, which appears to be the perfect solution. I've integrated the ddtf.js file into my project and code, following the example webpage instructions... but unfor ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...