If you click the button it changes the position on both elements but only the rect
has the animation.
JavaScript
x
4
1
function myFunction() {
2
document.getElementById("stackerCurrentSectBorder").setAttribute("y", "0%")
3
document.getElementById("stackerCurrentSectCurrShift").setAttribute("y", "10%")
4
}
JavaScript
1
3
1
#stackerCurrentSect * {
2
transition: .5s ease;
3
}
JavaScript
1
10
10
1
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
2
<g id="stackerCurrentSect" ref="stackerCurrentSect">
3
<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" />
4
<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>
5
</g>
6
</svg>
7
8
<button onclick="myFunction()">Click me</button>
9
10
<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):
JavaScript
1
4
1
function myFunction() {
2
document.getElementById("stackerCurrentSectBorder").style.transform = "translateY(-30%)"
3
document.getElementById("stackerCurrentSectCurrShift").style.transform = "translateY(-40%)"
4
}
JavaScript
1
3
1
#stackerCurrentSect * {
2
transition: .5s ease;
3
}
JavaScript
1
10
10
1
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
2
<g id="stackerCurrentSect" ref="stackerCurrentSect">
3
<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" />
4
<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>
5
</g>
6
</svg>
7
8
<button onclick="myFunction()">Click me</button>
9
10
<p id="demo"></p>