Loading
Interactivity and Animation in SVG-tutorial
SVG (Scalable Vector Graphics) is not just for static shapes it also supports animation and interactivity, making graphics dynamic and engaging on web pages.



SVG Animation using <animate>  

SVG has a built-in <animate> tag that lets you change the attributes of elements over time no JavaScript required.


Example:

<svg width="500" height="500">
   <circle cx="250" cy="250" r="50" fill="red">
      <animate attributeName="cx" from="50" to="450" dur="5s" repeatCount="indefinite" />
   </circle>
</svg>


Explanation:

  • <animate> : An SVG element used to animate a specific attribute. 
  • attributeName="cx": Animates the circle’s horizontal position. 
  • from="50": The animation starts with cx at 50. 
  • to="450": It ends with cx at 450. 
  • dur="5s": The transition duration is 5 seconds. 
  • repeatCount="indefinite": The animation runs continuously.



SVG Interactivity with Inline Event Handlers

You can make SVG elements react to user actions (like hover or click) using inline JavaScript.


Example:

<svg width="500" height="500">
   <circle cx="250" cy="250" r="50" fill="red" onmouseover="this.setAttribute('fill', 'blue');"
      onmouseout="this.setAttribute('fill', 'red');" onclick="alert('Circle clicked!')" />
</svg>


Explanation:

  • onmouseover: Changes the fill color to blue when the mouse is over the circle.
  • onmouseout: Changes the fill color back to red when the mouse leaves.
  • onclick: Shows an alert box when the circle is clicked.

Output:

Uploaded Image


After hover on the circle

Uploaded Image



Key Point

  • SVG animation works without CSS or JS using <animate>
  • For interactivity, you can use inline JavaScript events directly on SVG elements. 
  • These features help you build engaging visuals for modern web interfaces.