11

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 ...

ramesh
  • 4,008
  • 13
  • 72
  • 117

2 Answers2

14

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 can use in the step function.

$('#btn').click(function(){
    const $image = $('#dice_1');
    $image.animate(
        { 'foo': 200 },
        {
          step: (foo) => $image.attr('x', foo),
          duration: 2000
        }
    );
});
Sygmoral
  • 7,021
  • 2
  • 23
  • 31
  • This only works if the value you want to give is a number, cause the step function only takes a number. – Liora Haydont Feb 05 '18 at 18:30
  • Ehhh, this will do... thankfully css has the `rgb()` css function, so I can create a changing svg fill this way... – Shmack Nov 06 '21 at 00:44
7

jQuery animate is for animating HTML elements. For SVG you have to try jQuery SVG plugin. Please follow the link - http://keith-wood.name/svg.html

Arjun Raj
  • 984
  • 2
  • 12
  • 32
  • 2
    To be more precise, jQuery animate is for animating CSS properties. Some CSS can apply to SVG elements, such as opacity, fill, stroke. See [this article](http://www.smashingmagazine.com/2014/11/styling-and-animating-svgs-with-css/) for some explanation. – Sygmoral Dec 27 '15 at 03:57