Search code examples
javascripthtmlcsscss-transforms

Using multiple .style.transform on same element


It seems that by using two cases of obj.style.transform in succession results in only the first statement being executed. Please see the below code. A full example is on CodePen.

function animateObject(x, y, z){
    object = document.getElementsByClassName('cub-1')[0];

    object.style.transform = "rotateX(" + x + "deg)";
    object.style.transform = "rotateY(" + y + "deg)";
    alert("")
}

In the full example, I am reading lines from a text area which contains x, y and z positions of an object, converting the values from radians to degrees and then animating my 3d object using these values.


Solution

  • When applying multiple transforms to the same element, they should be added as space separated values to the same property like below. Otherwise, they would get overwritten (only the rotateY will be applied because it is the latest).

    object.style.transform = "rotateX(" + x + "deg)";
    object.style.transform += "rotateY(" + y + "deg)";
    

    I have added an alert of the object.style.transform to both the original snippet and the modified version and we can see how the original one always outputs only the rotateY whereas the changed one outputs both rotateX() and rotateY() together.

    Original Code with Alerts added | Modified Code with Alerts added