Chapter 29: SVG Scripting
SVG Scripting means adding JavaScript (or in very rare cases VBScript – but we ignore that today) directly inside or connected to SVG so that your SVG graphics become interactive, dynamic, and smart.
In simple words:
- Normal SVG = static picture (shapes, colors, gradients, text, patterns)
- SVG + Scripting = living, breathing graphic that can react to mouse clicks, hovers, keyboard, time, data changes, user input, API responses, etc.
This is how real-world applications create:
- Interactive charts & graphs (hover tooltips, zoom, click to filter)
- Clickable icons & buttons inside SVG
- Animated loaders that respond to progress
- Draggable/resizable elements
- Real-time data visualization (stock charts, maps, dashboards)
- Games or puzzles made only with SVG + JS
- Custom controls (sliders, knobs, gauges) that feel native
1. Three Main Ways to Add Scripting to SVG (2026 Reality)
| Method | Where the JavaScript lives | Best for | Most common in 2026? |
|---|---|---|---|
| 1. Inline <script> inside SVG | Directly inside <svg> tag | Self-contained SVG files | Yes – very common |
| 2. External JS file | <script src=”myscript.js”> inside SVG or HTML | Large projects, reusable code | Most professional use |
| 3. JavaScript in surrounding HTML | Normal <script> in HTML page that finds SVG elements | When SVG is inline in HTML | Extremely common |
→ Method 3 (JS in HTML) is the winner for almost every real website in 2026.
2. Your First SVG + Scripting Example (Copy-Paste & Try Now!)
Goal: Click the circle → it changes color randomly
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SVG Scripting – First Click Example</title> <style> circle:hover { cursor: pointer; } </style> </head> <body> <h1>Click the Circle – SVG + JavaScript</h1> <svg width="300" height="300" viewBox="0 0 300 300"> <circle id="myCircle" cx="150" cy="150" r="100" fill="orange" stroke="black" stroke-width="5"/> <!-- Optional: small text that will change --> <text id="info" x="150" y="170" font-size="24" text-anchor="middle" fill="white"> Click me! </text> </svg> <script> // 1. Find the SVG elements const circle = document.getElementById('myCircle'); const text = document.getElementById('info'); // 2. Array of fun colors const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96c93d', '#feca57', '#ff9ff3']; // 3. Add click event listener circle.addEventListener('click', () => { // Pick random color const randomColor = colors[Math.floor(Math.random() * colors.length)]; // Change fill color circle.setAttribute('fill', randomColor); // Change text text.textContent = 'Wow! ' + randomColor; // Bonus: little scale animation with CSS class circle.classList.add('pulse'); setTimeout(() => circle.classList.remove('pulse'), 300); }); </script> <style> .pulse { animation: pulse 0.3s ease; } @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.15); } 100% { transform: scale(1); } } </style> </body> </html> |
What happens:
- Click orange circle → it changes to random color
- Text updates
- Circle pulses (CSS animation triggered from JS)
This is SVG Scripting 101 — JavaScript finds SVG elements by id and changes attributes.
3. Most Common SVG Scripting Tasks (With Code Snippets)
A. Change attributes dynamically
|
0 1 2 3 4 5 6 7 8 |
circle.setAttribute('r', '120'); // bigger radius circle.setAttribute('fill', '#00ff00'); // green circle.setAttribute('transform', 'rotate(45 150 150)'); // rotate around center |
B. Hover / Mouse events
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
circle.addEventListener('mouseenter', () => { circle.setAttribute('stroke-width', '12'); circle.setAttribute('stroke', 'gold'); }); circle.addEventListener('mouseleave', () => { circle.setAttribute('stroke-width', '5'); circle.setAttribute('stroke', 'black'); }); |
C. Animate stroke drawing with JS (more control than CSS)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const path = document.querySelector('path'); const length = path.getTotalLength(); path.style.strokeDasharray = length; path.style.strokeDashoffset = length; function draw() { path.style.transition = 'stroke-dashoffset 3s ease-in-out'; path.style.strokeDashoffset = '0'; } |
Call draw() on button click or scroll.
D. Drag & Drop Shape
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
let isDragging = false; let startX, startY; circle.addEventListener('mousedown', (e) => { isDragging = true; startX = e.clientX; startY = e.clientY; }); document.addEventListener('mousemove', (e) => { if (!isDragging) return; const dx = e.clientX - startX; const dy = e.clientY - startY; const currentTransform = circle.getAttribute('transform') || ''; circle.setAttribute('transform', `{currentTransform} translate(${dx} ${dy})`); startX = e.clientX; startY = e.clientY; }); document.addEventListener('mouseup', () => { isDragging = false; }); |
4. Teacher’s Quick Summary Table
| Goal | Best Approach in 2026 | Library needed? |
|---|---|---|
| Simple hover/click changes | CSS :hover + JS event listeners | No |
| Path drawing / stroke animation | CSS keyframes (dashoffset) or JS | No / optional |
| Complex sequencing & timelines | GSAP (GreenSock) or Anime.js | Yes |
| Drag, resize, snap, physics | JavaScript + libraries (Interact.js, Draggable) | Yes |
| Real-time data update (charts) | D3.js, Chart.js, or custom JS | Usually yes |
5. Teacher’s Final Tips 😄
- Always give important SVG elements id or class → easy to find with document.getElementById or querySelector
- Use setAttribute() for SVG attributes — not .style.fill (CSS style is separate)
- Prefer CSS for hover, simple transitions, media queries
- Use JavaScript when you need logic (random colors, calculations, API data)
- Test on mobile — touch events (touchstart, touchmove) are different from mouse
- Common mistake: Change style.fill instead of setAttribute(‘fill’, …) → works in some browsers but not reliably in SVG
Understood SVG Scripting now? This is where SVG stops being just a picture and becomes a real interactive component of your website.
Tell me what you want next:
- Full draggable/resizable SVG shape?
- Real-time clock made with SVG + JS rotation?
- Interactive chart (bar hover shows value)?
- Click to add new circles randomly?
- Or complete animated icon set with hover + click?
Just say — we can script any SVG behavior together right now! 🚀
