Animating SVG with jQuery

Although SVG elements can actually be animated using SMIL, sometimes it's preferable to use another approach. In this case we're going to use jQuery to animate a simple SVG graphic. Before we get through this topic, there are a couple of things that you have to know. First of all, you have to serve your documents as application/xhtml+xml. In fact, SVG doesn't work if you use text/html. Second, your documents must be well-formed or you get an XML parsing error. Now let's start with a simple SVG image embedded in an XHTML document:

<svg width="300px" height="300px" version="1.1" xmlns="" id="svg-img">

   <desc>Sample logo</desc>
     <filter id="dropshadow">
      <feGaussianBlur result="blurredAlpha" in="SourceAlpha" stdDeviation="3" />
      <feOffset result="offsetBlurredAlpha" in="blurredAlpha" dx="3" dy="3" />
      <feFlood result="flooded" style="flood-color: black; flood-opacity: 0.65" />
      <feComposite result="coloredShadow" in="flooded" operator="in" in2="offsetBlurredAlpha" />
      <feComposite in="SourceGraphic" operator="over" in2="coloredShadow" />
    <polygon points="114, 61, 87, 211, 140, 211" style="filter: url(#dropshadow); stroke: #ddd; stroke-width: 1;
    stroke-opacity: 1; fill: #ccc; fill-opacity: 1;" />

Now we can use jQuery:

$(document).ready(function() {

    $('#svg-img').css('position', 'relative');

    $('#animate').click(function(e) {
     left: '100px',
     height: '0',
     width: '0',
     opacity: 'toggle'
     }, 'slow');


This example works as expected in Opera, Safari and Chrome. Firefox 3.6 simply makes the SVG image disappear. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.