Skip to content
Advertisement

CSS transition animation is not applied on inline svg but on it works fine?

If you click the button it changes the position on both elements but only the rect has the animation.

function myFunction() {
  document.getElementById("stackerCurrentSectBorder").setAttribute("y", "0%")
  document.getElementById("stackerCurrentSectCurrShift").setAttribute("y", "10%")
}
#stackerCurrentSect * {
  transition: .5s ease;
}
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
  <g id="stackerCurrentSect" ref="stackerCurrentSect">
    <rect x="30%" y="30%" width="31%" height="45%" rx="20" ry="20" fill="black" stroke="rgb(200,50,50)" stroke-width="1px" id="stackerCurrentSectBorder" ref="stackerCurrentSectBorder" />
    <text x="50%" y="50%" fill="rgb(120,120,120)" alignment-baseline="baseline" text-anchor="middle" font-size="80%" id="stackerCurrentSectCurrShift" ref="stackerCurrentSectCurrShift">current shift</text>
  </g>
</svg>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

Advertisement

Answer

To use a CSS transition, you need a CSS property to animate. The <text> x and y attributes are not. (Mainly, because they can take a list of values that position glyphs individually.)

In addition, x and y for the <rect> element have only been defined as CSS properties in the SVG 2 spec, which isn’t yet fully implemented by all browsers.

You can easily use a transform property instead. But you must set the style property, not the attribute, because the attribute does not take unit identifiers (yet):

function myFunction() {
  document.getElementById("stackerCurrentSectBorder").style.transform = "translateY(-30%)"
  document.getElementById("stackerCurrentSectCurrShift").style.transform = "translateY(-40%)"
}
#stackerCurrentSect * {
  transition: .5s ease;
}
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
  <g id="stackerCurrentSect" ref="stackerCurrentSect">
    <rect x="30%" y="30%" width="31%" height="45%" rx="20" ry="20" fill="black" stroke="rgb(200,50,50)" stroke-width="1px" id="stackerCurrentSectBorder" ref="stackerCurrentSectBorder" />
    <text x="50%" y="50%" fill="rgb(120,120,120)" alignment-baseline="baseline" text-anchor="middle" font-size="80%" id="stackerCurrentSectCurrShift" ref="stackerCurrentSectCurrShift">current shift</text>
  </g>
</svg>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement