I have a transition animation I want to trigger on the width of an SVG element inside a group element. The animation only seems to work on the Chrome browser.
<!-- works -->
<svg width="400" height="100">
<rect id="rect-1" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
<!-- only works in Chrome -->
<svg width="400" height="400">
<defs>
<g id="my-rect">
<rect id="rect-2" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</g>
</defs>
<use xlink:href="#my-rect" y="0"/>
<use xlink:href="#my-rect" y="110"/>
</svg>
.grow {
-webkit-transition: 1.5s;
-moz-transition: 1.5s;
-o-transition: 1.5s;
transition: 3s;
width: 10px;
}
(() => {
setTimeout(() => {
const rect1 = document.getElementById('rect-1');
rect1.classList.add('grow');
const rect2 = document.getElementById('rect-2');
rect2.classList.add('grow');
}, 1000);
})();
To reproduce open this fiddle in Safari or Firefox. You will see that the transition of the second rectangle does not work properly.
Is there any workaround to get the transition animation working for a specific element inside the SVG group?
Summarising, a workaround is to fall back to SMIL SVG animations instead of using CSS.
See the adapted fiddle to my original question.
<svg width="400" height="100">
<rect id="rect-1" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
<svg width="400" height="400">
<defs>
<g id="my-rect">
<rect id="g-rect" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)"/>
</g>
</defs>
<use xlink:href="#my-rect" y="0"/>
<use xlink:href="#my-rect" y="110"/>
</svg>
(() => {
setTimeout(() => {
const rect1 = document.getElementById('rect-1');
rect1.classList.add('grow');
const groupRect = document.getElementById('g-rect');
const growAnimation = document.createElementNS('http://www.w3.org/2000/svg', 'animate')
growAnimation.setAttribute('attributeName', 'width');
growAnimation.setAttribute('from', '400');
growAnimation.setAttribute('to', '10');
growAnimation.setAttribute('dur', '3s');
growAnimation.setAttribute('fill', 'freeze');
growAnimation.setAttribute('begin', 'indefinite');
groupRect.appendChild(growAnimation);
growAnimation.beginElement();
}, 1000);
})();