S.W S.W - 3 months ago 9
CSS Question

How to rotate an image with CSS style transform by an variable of degree?

var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
console.log("hour"+h+"min"+m+"sec"+s);

document.getElementById("sec").style.transform = "rotate((s*6)deg)";


I am trying to rotate an image with ID sec by (current second*6) degree. But it seems css rotate can only take a constant degree like rotate(40deg).
If I do
var x =40; rotate('x'deg);

or something like that its not going to work.

How do I let it rotate with an variable?

Jim Jim
Answer

What you are doing is supplying a string of rotate((s*6)deg) (literally with the S*6 instead of the result) into the transform style. You need to split the string so that it concatenates the result into the string.

Use this:

ar today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
console.log("hour"+h+"min"+m+"sec"+s);

document.getElementById("sec").style.transform = "rotate(" + (s*6) + "deg)";

This will pass the value of the variable s times 6 into the string. So instead of the CSS parser questioning what the literal string s*6deg means, it will instead recieve 120deg (if the variable s were the value 20) which is a valid CSS value. It is the same concept you were using in your console.log call one line above.