jQuery animate SVG element

ramesh picture ramesh · Aug 3, 2012 · Viewed 27.8k times · Source

I got a svg in my application. Like

<svg id="gt" height="450" width="300" xmlns="http://www.w3.org/2000/svg">
<image id="1_dice" x="0" y="420" height="30" width="30" xlink:href="images/1_coin.png" />
</svg>

I got a svg element named '1_dice'. In a HTML button click I would likes to animate the element according to the parameters. Like

$('#btn').click(function(){
     $('#1_dice').animate({'x':200},2000);
});

I tried this but this doesn't working ...

Answer

Sygmoral picture Sygmoral · Dec 27, 2015

It is possible without a plugin, but it involves a trick then. The issue is that x is not a css property but an attribute, and jQuery.animate only animates css properties. But you can use the step parameter to specify your own custom behavior for the animation.

foo is a non-existing property whose animating value we use in the step function.

$('#btn').click(function(){
    $('#dice_1').animate(
        {'foo':200},
        {
            step: function(foo){
                 $(this).attr('x', foo);
            },
            duration: 2000
        }
    );
});