SVG Countdown class
by jorgeluis
HTML
<div id="countdown" class="countdown">
<label>0</label>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle id="circle" class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
</g>
</svg>
</div>
<button id="start">Start</button>
<button id="restart">Restart</button>
CSS
.countdown {
position: relative;
width: 160px;
height: 160px;
float: left;
}
.countdown label {
position: absolute;
width: 100%;
text-align: center;
font: 40px/160px sans-serif;
color: tomato;
}
svg {
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
#circle {
fill: rgba(120,120,120,0.1);
stroke-width: 8px;
stroke: #6fdb6f;
fill: none;
stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
stroke-dashoffset: 440; /* these values need to match html attrs */
transition: all 1s linear;
}
JavaScript
function Countdown (time, callback) {
this.time = time;
this.callback = callback;
this.el = document.getElementById('countdown');
this.circ = this.el.querySelector('#circle');
this.radius = parseInt(this.circ.getAttribute('r'), 10);
this.circumference = 2 * 3.14159 * this.radius + parseInt(this.circ.getAttribute('stroke-width'), 10);
}
Countdown.prototype.start = function() {
var c = this;
var i = 1;
// Need initial run as interval hasn't yet occured...
c.circ.style.strokeDashoffset = c.circumference - ( 1 * (c.circumference/c.time) );
interval = setInterval(function() {
c.el.querySelector('label').textContent = i;
if (i == c.time) {
clearInterval(interval);
if (typeof c.callback == 'function') {
c.callback();
}
return;
}
c.circ.style.strokeDashoffset = c.circumference - ( (i+1) * (c.circumference/c.time) );
i++;
}, 1000);
}
Countdown.prototype.restart = function() {
var c = this;
clearInterval(interval);
c.start(c.time, c.callback);
}
var cd = new Countdown(12, function() { console.debug('done'); });
// window.setTimeout(cd.restart(), 6000);
var startButton = document.querySelector('#start');
var restartButton = document.querySelector('#restart');
startButton.addEventListener('click', cd.start() );
restartButton.addEventListener('click', cd.restart() );