Dressing Up Your Data: Building Animated Circular Gauges in Storyline
When off-the-shelf Storyline widgets don't cut it, sometimes you have to build your own. This deep dive walks through creating a fully animated, scrubbable circular gauge using SVG, GSAP, and vanilla JavaScript—complete with responsive scaling, memory management, and seamless timeline integration.
By Nathan Stoker · Published Feb 22, 2026 · Updated Nov 8, 2026 · 5 min read

A Deep Dive into Custom SVG Animations with GSAP and Timeline Scrubbing
Sometimes building e-learning feels like being a monster in a clothing store—you know what you want to wear, but nothing off the rack quite fits. That's exactly how I felt when I needed an animated circular gauge for an Articulate Storyline project. The built-in options were too basic. Third-party widgets didn't play nice with timeline scrubbing. So I rolled up my sleeves and built one from scratch.
What emerged was a fully scrubbable, auto-playing circular gauge that syncs perfectly with Storyline's seekbar. Let me walk you through how it works.
The Challenge
Storyline is fantastic for rapid e-learning development, but when you need custom visualizations that go beyond stock assets, you're on your own. I needed a gauge that could:
Animate from 0% to any target value
Respond to timeline scrubbing (so learners could rewind and replay)
Resize dynamically
Not break Internet Explorer compatibility (yes, some enterprises still require it)
The solution? Pure JavaScript, SVG, and GSAP—all wrapped in a tidy IIFE (Immediately Invoked Function Expression) to keep things clean.
Anatomy of the Gauge
Configuration That Makes Sense
The first thing you'll notice is the user settings block at the top. This is where the magic happens for customization:
const PLACEHOLDER_ID = '6lpablI3pfZ';
const TARGET_PERCENT = 60;
const ANIM_DURATION = 2;
const START_TIME = 0.25;
const AUTO_PLAY = true;
The PLACEHOLDER_ID points to a Storyline object (grab this from the data-model-id attribute in your published output). The gauge will render inside this container, inheriting its size. TARGET_PERCENT, ANIM_DURATION, and START_TIME give you precise control over the animation behavior.
SVG Magic with Dynamic Scaling
The gauge is built with two concentric circles: an inner gray track and an outer purple progress arc. What makes this implementation special is dynamic stroke scaling:
const INNER_STROKE_RATIO = 0.055;
const OUTER_STROKE_RATIO = 0.095;
// Later in buildGauge():
const INNER_STROKE = SIZE * INNER_STROKE_RATIO;
const OUTER_STROKE = SIZE * OUTER_STROKE_RATIO;By using ratios instead of fixed pixel values, the gauge maintains perfect proportions at any size. Whether your placeholder is 200px or 800px, the stroke widths scale proportionally.
The Secret Sauce: Seekbar Binding
Here's where things get interesting. Storyline has a progress bar that shows the current timeline position. By hooking into this element, we can make our gauge scrubbable:
const fill = document.querySelector(
'div[data-ref="progressBarFill"]'
);
// Extract width percentage from inline style
const m = /width:\s*([\d.]+)%/.exec(style);
const t = (parseFloat(m[1]) / 100) * duration;
tl.progress(p, false);The function runs in a requestAnimationFrame loop, continuously reading Storyline's progress bar and updating the GSAP timeline accordingly. When a learner drags the seekbar backward, the gauge animates backward too. It's seamless.
Defensive Programming Wins
Version 3.1 introduced comprehensive fixes for real-world edge cases. Memory leaks were addressed by tracking all resources (animation loops, timelines, resize handlers) in a cleanup object:
const cleanup = {
animationLoop: null,
timeline: null,
delayedCall: null,
resizeHandler: null
};Input validation catches configuration errors before they cause cryptic failures. The percentage is clamped between 0 and 100 to prevent overflow. And the waitForStableSize function ensures the container has actually rendered before we try to measure it—a common gotcha in Storyline's async rendering environment.
Typography That Pops
The gauge uses Oswald, a bold condensed typeface that reads well at various sizes. The font is injected dynamically via a Google Fonts @font-face rule:
const FONT_FAMILY = '"Oswald", sans-serif';
'font-size': SIZE * 0.26 // Scales with gaugeThe font size scales at 26% of the gauge diameter, ensuring the percentage text is always proportional and legible.
Using It in Your Projects
To implement this in your own Storyline project:
Create a rectangle or group where you want the gauge to appear
Publish your project and find the
data-model-idof that object in the HTMLUpdate
PLACEHOLDER_IDin the codeAdd the script via Execute JavaScript trigger on slide load
Adjust
TARGET_PERCENT, colors, and timing to match your design
The gauge will handle the rest, including responsive resizing and seekbar synchronization.
The Full Code
Here's the complete implementation. Copy this into an Execute JavaScript trigger, update the PLACEHOLDER_ID and settings to match your project, and you're ready to go:
/******************************************************************
* Storyline Circular Gauge ♦ v3.1 - COMPREHENSIVE FIX
* - Uses Oswald (Google Fonts)
* - Scrubbable + manually triggered
* - Fixed initialization hiccup
* - FIXED: Memory leaks, resize handling, percentage overflow
* - FIXED: Infinite loops, error handling, cleanup
* - FIXED: Dynamic stroke scaling on resize
******************************************************************/
(function () {
/* ───── USER SETTINGS ───── */
const PLACEHOLDER_ID = '5jwc7xJ7HKc'; // ← your rectangle/group data-model-id
const TARGET_PERCENT = 60; // 0-100 or Storyline variable
const ANIM_DURATION = 2; // seconds
const START_TIME = 0.25; // seconds
const AUTO_PLAY = true; // true = auto-start, false = scrub only
const FONT_FAMILY = '"Oswald", sans-serif';
const INNER_STROKE_RATIO = 0.055; // Relative to gauge size (21/380 ≈ 0.055)
const OUTER_STROKE_RATIO = 0.095; // Relative to gauge size (36/380 ≈ 0.095)
const COLOR_INNER = '#a6a6a6';
const COLOR_OUTER = '#8064A2';
/* ───── CONFIGURATION ───── */
const CONFIG = {
MAX_SIZE_CHECK_RETRIES: 60,
SIZE_CHECK_STABLE_COUNT: 3,
RESIZE_DEBOUNCE_MS: 150,
MAX_DURATION_RETRIES: 40,
DURATION_RETRY_INTERVAL: 50,
DEFAULT_SLIDE_DURATION: 10,
SIZE_RETRY_DELAY: 100,
FADE_IN_DURATION: 0.3,
TIMELINE_DELAY: 0.1
};
/* ───── GLOBAL STATE ───── */
let gaugeInstance = null;
/* ───── FONT INJECTION ───── */
function injectFont_Oswald() {
if (document.getElementById('oswald-font')) return;
const style = document.createElement('style');
style.id = 'oswald-font';
style.textContent = `
@font-face {
font-family: 'Oswald';
font-style: normal;
font-weight: 400;
src: url('https://fonts.gstatic.com/s/oswald/v53/TK3_WkUHHAIjg75cFRf3bXL8LICs1_FvsUtiZTaR.woff2') format('woff2');
font-display: swap;
}
`;
document.head.appendChild(style);
}
/* ───── HELPERS ───── */
const $ = (id) => document.querySelector(`[data-model-id="${id}"]`);
function validateInputs() {
const errors = [];
if (typeof TARGET_PERCENT !== 'number' || isNaN(TARGET_PERCENT)) {
errors.push('TARGET_PERCENT must be a valid number');
}
if (TARGET_PERCENT < 0 || TARGET_PERCENT > 100) {
errors.push('TARGET_PERCENT must be between 0 and 100');
}
if (typeof ANIM_DURATION !== 'number' || ANIM_DURATION <= 0) {
errors.push('ANIM_DURATION must be a positive number');
}
if (typeof START_TIME !== 'number' || START_TIME < 0) {
errors.push('START_TIME must be a non-negative number');
}
return errors;
}
function ensureGSAP(cb) {
if (window.gsap) return cb();
const s = document.createElement('script');
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js';
s.onload = () => cb();
s.onerror = () => {
console.error('Gauge: Failed to load GSAP library');
};
document.head.appendChild(s);
}
function bindToStorylineSeekbar(tl, duration, cleanup) {
const fill = document.querySelector('div[data-ref="progressBarFill"]');
if (!fill) {
console.warn('Gauge: Progress bar fill not found, scrubbing disabled');
return null;
}
let rafId = null;
function loop() {
try {
const style = fill.getAttribute('style');
if (!style) {
rafId = requestAnimationFrame(loop);
return;
}
const m = /width:\s*([\d.]+)%/.exec(style);
if (m) {
const t = (parseFloat(m[1]) / 100) * duration;
const p = Math.max(0, Math.min((t - START_TIME) / ANIM_DURATION, 1));
tl.progress(p, false);
}
} catch (e) {
console.error('Gauge: Error in seekbar binding:', e);
}
rafId = requestAnimationFrame(loop);
}
rafId = requestAnimationFrame(loop);
// Store cleanup function
cleanup.animationLoop = () => {
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
};
return rafId;
}
function getSlideDuration(cb, retries = 0) {
if (retries >= CONFIG.MAX_DURATION_RETRIES) {
console.warn('Gauge: Could not detect slide duration, using default:', CONFIG.DEFAULT_SLIDE_DURATION);
return cb(CONFIG.DEFAULT_SLIDE_DURATION);
}
const r = document.querySelector('input[type="range"][data-ref="progressBar"]');
if (!r) {
setTimeout(() => getSlideDuration(cb, retries + 1), CONFIG.DURATION_RETRY_INTERVAL);
return;
}
const m = parseFloat(r.max || r.getAttribute('max'));
if (!isNaN(m) && m > 0) {
return cb(m / 1000);
}
setTimeout(() => getSlideDuration(cb, retries + 1), CONFIG.DURATION_RETRY_INTERVAL);
}
function waitForStableSize(container, cb, retries = 0) {
let lastWidth = 0, lastHeight = 0, stableCount = 0;
function checkSize() {
if (retries >= CONFIG.MAX_SIZE_CHECK_RETRIES) {
console.error('Gauge: Timeout waiting for stable container size');
return;
}
const rect = container.getBoundingClientRect();
if (rect.width === lastWidth && rect.height === lastHeight && rect.width > 0) {
stableCount++;
if (stableCount >= CONFIG.SIZE_CHECK_STABLE_COUNT) {
return cb(rect);
}
} else {
stableCount = 0;
}
lastWidth = rect.width;
lastHeight = rect.height;
retries++;
requestAnimationFrame(checkSize);
}
checkSize();
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function buildGauge(container, percent) {
percent = Math.max(0, Math.min(100, percent));
// Cleanup object to track all resources
const cleanup = {
animationLoop: null,
timeline: null,
delayedCall: null,
resizeHandler: null
};
// Clean up any existing gauge
const existingWrapper = container.querySelector('.gauge-wrapper');
if (existingWrapper) {
existingWrapper.remove();
}
// Wait for container to have stable dimensions
waitForStableSize(container, (rect) => {
try {
const { width, height } = rect;
const SIZE = Math.min(width, height);
if (SIZE <= 0) {
console.warn('Gauge: Container has no dimensions, retrying...');
setTimeout(() => buildGauge(container, percent), CONFIG.SIZE_RETRY_DELAY);
return;
}
// Hide original content smoothly
const originalContent = Array.from(container.children).filter(el =>
!el.classList.contains('gauge-wrapper')
);
originalContent.forEach(el => {
el.style.opacity = '0';
el.style.pointerEvents = 'none';
});
const wrap = Object.assign(document.createElement('div'), {
className: 'gauge-wrapper',
style: `position:absolute;top:0;left:0;width:${SIZE}px;height:${SIZE}px;pointer-events:none;opacity:0;`
});
container.appendChild(wrap);
const NS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('width', SIZE);
svg.setAttribute('height', SIZE);
wrap.appendChild(svg);
const makeCircle = (r, stroke, color, outer) => {
const c = document.createElementNS(NS, 'circle');
Object.entries({
cx: SIZE / 2, cy: SIZE / 2, r,
fill: 'none', stroke: color, 'stroke-width': stroke,
'stroke-linecap': 'butt',
transform: outer ? `rotate(-90 ${SIZE/2} ${SIZE/2})` : ''
}).forEach(([k, v]) => c.setAttribute(k, v));
svg.appendChild(c);
return c;
};
// Calculate dynamic stroke widths based on gauge size
const INNER_STROKE = SIZE * INNER_STROKE_RATIO;
const OUTER_STROKE = SIZE * OUTER_STROKE_RATIO;
const r1 = (SIZE / 2) - (INNER_STROKE / 2) - (OUTER_STROKE / 2);
const r2 = r1 + (INNER_STROKE / 2) + (OUTER_STROKE / 2);
const inner = makeCircle(r1, INNER_STROKE, COLOR_INNER);
const outer = makeCircle(r2, OUTER_STROKE, COLOR_OUTER, true);
const CIRC = 2 * Math.PI * r2;
outer.setAttribute('stroke-dasharray', CIRC);
outer.setAttribute('stroke-dashoffset', CIRC);
const txt = document.createElementNS(NS, 'text');
Object.entries({
x: SIZE/2, y: SIZE/2, 'text-anchor':'middle',
'dominant-baseline':'central',
'font-family': FONT_FAMILY,
'font-size': SIZE * 0.26,
fill: COLOR_INNER
}).forEach(([k, v]) => txt.setAttribute(k, v));
txt.textContent = '0%';
svg.appendChild(txt);
// Set initial states - everything invisible
gsap.set([outer, inner, txt], { opacity: 0 });
gsap.set(wrap, { opacity: 1 });
// Create the main timeline
const tl = gsap.timeline({ paused: true });
cleanup.timeline = tl;
// Add a brief delay at the start to ensure clean timeline scrubbing
tl.to({}, { duration: CONFIG.TIMELINE_DELAY }, 0)
.fromTo([outer, inner, txt],
{ opacity: 0 },
{ opacity: 1, duration: CONFIG.FADE_IN_DURATION, ease: 'power2.out' },
CONFIG.TIMELINE_DELAY
)
.to(outer, {
strokeDashoffset: CIRC * (1 - percent / 100),
duration: ANIM_DURATION,
ease: 'power2.out'
}, CONFIG.TIMELINE_DELAY)
.to({}, {
duration: ANIM_DURATION,
ease: 'none',
onUpdate() {
const currentTime = tl.time();
if (currentTime >= CONFIG.TIMELINE_DELAY) {
// FIX: Clamp animProgress to prevent overflow
const animProgress = Math.max(0, Math.min(1, (currentTime - CONFIG.TIMELINE_DELAY) / ANIM_DURATION));
const p = Math.round(animProgress * percent);
txt.textContent = p + '%';
} else {
txt.textContent = '0%';
}
}
}, CONFIG.TIMELINE_DELAY);
getSlideDuration((dur) => {
bindToStorylineSeekbar(tl, dur, cleanup);
if (AUTO_PLAY) {
cleanup.delayedCall = gsap.delayedCall(START_TIME, () => tl.play());
}
});
// Store cleanup function on container
container._gaugeCleanup = () => {
if (cleanup.animationLoop) cleanup.animationLoop();
if (cleanup.timeline) cleanup.timeline.kill();
if (cleanup.delayedCall) cleanup.delayedCall.kill();
if (cleanup.resizeHandler) {
window.removeEventListener('resize', cleanup.resizeHandler);
}
};
} catch (e) {
console.error('Gauge: Error building gauge:', e);
}
});
}
/* ───── RESIZE HANDLER ───── */
function setupResizeHandler(container, percent) {
const handleResize = debounce(() => {
console.log('Gauge: Resizing...');
// Clean up old gauge
if (container._gaugeCleanup) {
container._gaugeCleanup();
}
// Rebuild gauge with current percentage
buildGauge(container, percent);
}, CONFIG.RESIZE_DEBOUNCE_MS);
window.addEventListener('resize', handleResize);
// Store for cleanup
if (container._gaugeCleanup) {
const oldCleanup = container._gaugeCleanup;
container._gaugeCleanup = () => {
oldCleanup();
window.removeEventListener('resize', handleResize);
};
}
}
/* ───── EXECUTE ───── */
function init() {
try {
// Validate inputs
const errors = validateInputs();
if (errors.length > 0) {
console.error('Gauge: Configuration errors:', errors);
return;
}
const container = $(PLACEHOLDER_ID);
if (!container) {
console.error('Gauge: placeholder not found:', PLACEHOLDER_ID);
return;
}
// Clean up previous instance if exists
if (gaugeInstance && gaugeInstance._gaugeCleanup) {
gaugeInstance._gaugeCleanup();
}
gaugeInstance = container;
injectFont_Oswald();
ensureGSAP(() => {
// Small delay to ensure everything is loaded
requestAnimationFrame(() => {
buildGauge(container, TARGET_PERCENT);
setupResizeHandler(container, TARGET_PERCENT);
});
});
} catch (e) {
console.error('Gauge: Initialization error:', e);
}
}
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// Global cleanup for debugging/testing
window.destroyGauge = () => {
if (gaugeInstance && gaugeInstance._gaugeCleanup) {
gaugeInstance._gaugeCleanup();
console.log('Gauge: Destroyed');
}
};
})();Final Thoughts
Custom JavaScript in Storyline opens up a world of possibilities beyond the standard toolkit. This circular gauge started as a simple need—show a percentage with some visual flair—and evolved into a robust, production-ready component with proper cleanup, error handling, and responsive design.
Like that monster finding the perfect outfit, sometimes you just have to tailor your own solution. The fit is always better when it's made just for you.
Happy coding!
Nathan Stoker
I build custom eLearning in Storyline, Rise and JavaScript, and I make the free tools and templates on this site. Need an interaction like this in your course? Let's talk.