In this post, I’ll give the code to create a Circular progress bar which I tried with a Start button and it resets every time you click on the start button and ticks every second for 60 seconds. The start button is shown using media control html code. The start button will re-appear once timer is reset.
If you’re using Asp.net Core MVC template, I’ve put the below code in index.cshtml file.
The HTML is as below:
< div >
< svg class="progress-ring"
width="120"
height="120" >
< circle class="progress-ring__circle"
stroke="orange"
stroke-width="4"
fill="transparent"
r="58"
cx="60"
cy="60" / >
< text id="play" x="40" y="70" onclick="startTimer()" >▶< /text >
< /svg >
< /div >
Css is as follows in the site.css file:
.progress-ring {
}
.progress-ring__circle {
transition: 0.35s stroke-dashoffset;
transform-origin: 50% 50%;
}
#play {
cursor: pointer;
font-size: xx-large;
}
The below Javascript code is going to modify the svg stroke-dashoffset attribute as below in the site.js file:
var i = 0;
var interval;
var circle = document.querySelector('circle');
var radius = circle.r.baseVal.value;
var circumference = radius * 2 * Math.PI;
console.log('radius', radius);
console.log('circumference', circumference);
circle.style.strokeDasharray = `${circumference} ${circumference}`;
circle.style.strokeDashoffset = `${circumference}`;
function setProgress(percent) {
const offset = circumference - percent / 100 * circumference;
circle.style.strokeDashoffset = offset;
}
function startTimer() {
console.log('circumference', circumference);
circle.style.strokeDashoffset = `${circumference}`;
document.getElementById("play").textContent = "ok";
interval = setInterval(increment, 1000);
}
function increment() {
i = i % 360 + 1;
var perc = (i / 60) * 100;
console.log(i);
if (i === 60) {
clearInterval(interval);
document.getElementById("play").textContent = "\u25B6";
i = 0;
}
setProgress(perc);
}
The stroke-dashoffset value is reduced every time to increase the progress with stroke-dasharray. You can play around with the radius to increase the circle size.
One thought on “Circular Progress bar svg javascript”