2

I want to change my css style by JavaScript like i change transform: rotateZ(120deg);

<script>
    var Rotate = ['90deg','120deg','150deg','180deg','210deg','240deg','90deg','120deg','150deg','180deg','210deg','240deg'];
     function Time() {
         var marg, d, hour; 
         marg = document.getElementById("hand");  
         d = new Date(); 
         hour = d.getHours();
         for(i = 0; i < 12; i++) {
             if(hour == i) { 
                 var x=Rotate[i]; 
                 alert(x); 
                 marg.style.transform= "rotateZ(x)";
             }
         }
    }
</script>

alert(x) is working but transform is not working. Is there any way to use array list to change transform value?

3
  • 2
    try marg.style.transform= "rotateZ(" + x + ")" Commented Jun 29, 2016 at 11:47
  • "rotateZ(x)" is just a string -- you were not actually using the x variable at all! Commented Jun 29, 2016 at 11:55
  • "rotateZ("+Rotate[i]+")" is it working? Commented Jun 29, 2016 at 11:59

3 Answers 3

1

You are using "rotateZ(x)". Here x is not a variable for this script because you are writing it like string. Variables must be written outside ".

Use it like this

var Rotate = ['90deg', '120deg', '150deg', '180deg', '210deg', '240deg', '90deg', '120deg', '150deg', '180deg', '210deg', '240deg'];

function Time() {
    var marg, d, hour;
    marg = document.getElementById("hand");
    d = new Date();
    hour = d.getHours();
    for (i = 0; i < 12; i++) {
      if (hour == i) {
        var x = Rotate[i];
        alert(x);
        marg.style.transform = "rotateZ("+x+")";
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

"rotateZ(x)" in your code is a complete string. You need to change it to "rotateZ(" + x + ")" to make your code work.

You can use Array#forEach to simplify your task.

var Rotate = ['90deg', '120deg', '150deg', '180deg', '210deg', '240deg', '90deg', '120deg', '150deg', '180deg', '210deg', '240deg'];

function Time() {
    var marg, d, hour;

    marg = document.getElementById("hand");
    d = new Date();
    hour = d.getHours();

    Rotate.forEach(function(v, i) {
        if (hour == i) {
            alert(v);
            marg.style.transform = "rotateZ("+ v + ")";
        }
    });
}

Comments

0

I know that is beyond your question, but I think the best possible solution to solve the problem is using different css classes and only change the class name in js.

Fiddling with css properties in js seems really unneccessary to me :(

1 Comment

can you more describe ? or give me an example plz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.