jQuery animate SVG element
Asked Answered
Q

2

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

Quinnquinol answered 3/8, 2012 at 5:16 Comment(5)
If the DOCTYPE of the page is not HTML5 note that IDs must begin with a letter.Classic
thanks for the reply .. My DOCTYPE is <!DOCTYPE html> <html> <head> I also changes the name to "dice" . But not working .. even $('#dice').hide(); this is working.. plz helpQuinnquinol
$('#dice').hide(); -- this is working ... but animate is not workingQuinnquinol
oh sorry .. I m not Iranian ... m IndianQuinnquinol
no worries, cool, we have Ramesh in Persia too, beautiful name :)Classic
L
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

Leif answered 12/11, 2012 at 17:57 Comment(1)
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 for some explanation.Forayer
F
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
        }
    );
});
Forayer answered 27/12, 2015 at 3:51 Comment(2)
This only works if the value you want to give is a number, cause the step function only takes a number.Interracial
Ehhh, this will do... thankfully css has the rgb() css function, so I can create a changing svg fill this way...Chromatophore
L
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

Leif answered 12/11, 2012 at 17:57 Comment(1)
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 for some explanation.Forayer

© 2022 - 2024 — McMap. All rights reserved.