Interactive SVG Elements
Learn how to create interactive SVG graphics with event handling, animations, and user-driven changes.
What Makes SVG Interactive?
Interactive SVGs respond to user actions like mouse clicks, hovers, and touch gestures using JavaScript. You can:
- Change colors or shapes on hover
- Animate elements with user input
- Drag and drop SVG nodes
- Capture click events for UI components
Try This Interactive Example
Click the Circle
Click anywhere on the circle to change its color randomly.
<svg viewBox="0 0 300 300">
<circle cx="150" cy="150" r="80" fill="#4f46e5"
onclick="changeColor(this)" />
</svg>
<script>
function changeColor(el) {
const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
el.setAttribute('fill', randomColor);
}
</script>
Draggable SVG Elements
Drag the rectangle with your mouse or finger:
<svg viewBox="0 0 400 200">
<rect x="50" y="50" width="100" height="100"
onmousedown="startDrag(event)"
onmousemove="drag(event)"
onmouseup="endDrag(event)"
onmouseleave="endDrag(event)" />
</svg>
<script>
let isDragging = false;
let offset = {x:0, y:0};
function startDrag(e) {
isDragging = true;
const el = e.target;
offset.x = e.offsetX;
offset.y = e.offsetY;
}
function drag(e) {
if (!isDragging) return;
const el = document.getElementById('dragBox');
const rect = el.getBBox();
const svg = e.currentTarget;
el.setAttribute('x', e.clientX - rect.width/2);
el.setAttribute('y', e.clientY - rect.height/2);
}
function endDrag() {
isDragging = false;
}
</script>
Hover Effects in SVG
Grow on Hover
Circle expands when hover
Rounded on Hover
Rectangle corners round
Interactive SVG Code Patterns
Click Interactions
<svg>
<rect ... onclick="console.log('clicked!')"/>
<circle ... onmouseover="this.setAttribute('fill', 'red')" />
</svg>
Use standard DOM events with SVG elements to create custom interactions.
Drag-and-Drop
SVGElement.addEventListener('mousedown', ...) // Initiate drag
requestAnimationFrame(() => { // Animation loop
element.setAttribute('transform', 'translate(x,y)')
});
Implement complex dragging by tracking mouse coordinates and applying transforms.