javascriptjqueryanimationsvg

SVG animation cannot be triggered programmatically, without using an HTML button?


I have the following piece of code, that animates an SVG circle on click:

<circle id = "middle" cx="235" cy="235" r="100" stroke="yellow" stroke-width="0.5" fill="#ffcc00"> <animate begin="click" attributeName="fill" to="yellow" dur="1s"/>

It works fine when the user clicks inside the circle, but I would like to trigger the animation programmatically.

I tried $("#middle").click();, but the animation doesn't occur, even though the click event is issued. (I have also set $("#middle").click(function() { audio.play(); }); and the sound is played all right).

Is there a way to animate the SVG by simulating the user click (on the SVG), without using an HTML button?


Solution

  • Call beginElement if you want to start an animation programatically.

    <svg>
      <circle id = "middle" cx="50" cy="50" r="25" stroke="yellow" stroke-width="0.5" fill="#ffcc00">
      <animate id="a" begin="click" attributeName="fill" to="yellow" dur="1s"/>
    </circle>
    </svg>
    <button onclick="document.getElementById('a').beginElement();">>Click Me!</button>