I am trying to write some JavaScript code that scales a div element using the transform:scale() CSS property, and then un-scales it so that the element returns to its original size. I thought that if I scale the element by applying transform:scale(a), I could un-scale it by applying transform:scale(1/a), since (element x a) x (1 / a) = element. However, that does not seem to work. Why not?
function scale_up() {
document.getElementById("div").style.transform = "scale(3)";
}
function scale_down() {
document.getElementById("div").style.transform = "scale(0.33)";
}
setTimeout(scale_up, 3000)
setTimeout(scale_down, 6000) /* this should return the div to its original size, but it doesn't */
#div {
height: 30px;
width: 30px;
border-style: solid;
}
<body>
<div id="div"></div>
</body>
CSS is a declarative language, and thus applying new properties on a given element or selector replaces existing ones with the same property name; properties are not added or multiplied when you set them again.
CSS transforms, building upon this, work the same way: setting the transform to scale(3)
and then setting it to scale(0.33)
has the same effect as just setting it to scale(0.33)
: the latter transform replaces the former.
Applying this principle, to undo the transform you can simply remove the CSS property that applies it to your element; you can do this by simply setting the property to an empty string, as per this StackOverflow answer. Alternatively, in this case, you can simply set a scale of 1:
function scale_up() {
document.getElementById("div").style.transform = "scale(3)";
}
function scale_down() {
document.getElementById("div").style.transform = "";
// This would also work:
//document.getElementById("div").style.transform = "scale(1)";
}
setTimeout(scale_up, 3000)
setTimeout(scale_down, 6000)
#div {
height: 30px;
width: 30px;
border-style: solid;
}
<body>
<div id="div"></div>
</body>