Skip to content Skip to sidebar Skip to footer

Toggle Svg Animation Effect When Click The Button

I'm a SVG beginner so please bear with me. Basically, I wish to animate a triangle to move from top to bottom when click and move from bottom to top if click again. My problem is

Solution 1:

Here's a SMIL only answer. If you want IE support, add fakeSmile.

<svgviewBox="0 0 24 24"preserveAspectRatio="none"><polygonpoints="2,0  12,11  22,0"fill="#000"display="none"><animateid="a2"attributeName="points"attributeType="XML"from="2,0  12,11  22,0"to="2,-5  12,6  22,-5"begin="click"dur="0.5s"fill="freeze"></animate><setattributeName="display"to="block"begin="a1.end"fill="freeze" /><setattributeName="display"to="none"begin="a2.end"fill="freeze" /><setattributeName="points"to="2,0  12,11  22,0"begin="a2.end"fill="freeze" /></polygon><polygonpoints="2,-5  12,6  22,-5"fill="#000"><animateid="a1"attributeName="points"attributeType="XML"from="2,-5  12,6  22,-5"to="2,0  12,11  22,0"begin="click"dur="0.5s"fill="freeze"></animate><setattributeName="display"to="none"begin="a1.end"fill="freeze" /><setattributeName="points"to="2,-5  12,6  22,-5"begin="a1.end"fill="freeze" /><setattributeName="display"to="block"begin="a2.end"fill="freeze" /></polygon></svg>

Solution 2:

I think that it's not possible with basic svg animate elements, you will need javascript.

A dirty way could consist to add a second animate, which will make your element animate to the original step, and trigger the right animate.beginElement() method on click of your <polygon>.

But you will need to keep a reference of the current state you are in, so in the following example, I added a big_state property to the polygon object.

var poly = document.querySelector('polygon');
 poly.onclick = function() {
   var anims = this.querySelectorAll('animate');
   anims[+!!this.big_state].beginElement();
   this.big_state = !this.big_state;
 }
<svgviewBox="0 0 24 24"preserveAspectRatio="none"><scripttype="text/ecmascript"xlink:href="FakeSmile-master/smil.user.js" /><polygonpoints="2,-5  12,6  22,-5"fill="#000"><animateattributeName="points"attributeType="XML"from="2,-5  12,6  22,-5"to="2,0  12,11  22,0"begin="indefinite"dur="0.5s"fill="freeze"id="bigger" /><animateattributeName="points"attributeType="XML"from="2,0  12,11  22,0"to="2,-5  12,6  22,-5"begin="indefinite"dur="0.5s"fill="freeze"id="smaller" /></polygon></svg>

Post a Comment for "Toggle Svg Animation Effect When Click The Button"