Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS transitions to animate the position of SVG elements

I'd like to use CSS transitions to animate the position of SVG elements.

However - it looks like this works on some SVG elements (e.g., rect), but not on others (e.g. text):

document.querySelector("button").onclick = function() {
  var x = Math.random() * 450;
  document.querySelector("rect").setAttributeNS(null, "x", x);
  document.querySelector("text").setAttributeNS(null, "x", x);
}
rect {
  transition: all 700ms ease-in-out;
}

text {
  transition: all 700ms ease-in-out;
}
<svg width="500" height="100">
  <rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
  <text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>

Am I doing something wrong? Is there a better way to do this? (ideally, without using JavaScript or a library like GreenSock).

like image 798
mattstuehler Avatar asked Dec 09 '25 17:12

mattstuehler


1 Answers

You can use translation instead:

document.querySelector("button").onclick = function() {
  var x = Math.random() * 250;
  document.querySelector("rect").setAttributeNS(null, "transform","translate("+x+")");
  document.querySelector("text").setAttributeNS(null, "transform","translate("+x+")");
}
rect {
  transition: all 700ms ease-in-out;
}

text {
  transition: all 700ms ease-in-out;
}
<svg width="500" height="100">
  <rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
  <text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>
like image 110
Temani Afif Avatar answered Dec 12 '25 07:12

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!