sam sam - 4 months ago 22
CSS Question

'toggel' rotation of element back and forth using css3/jquery

i've got an image that i want to onclick animate the rotation 90degress, when its clicked again i want it to animate the rotation -90degrees.

For the rotation im using the css3 transform:

-moz-transform:rotate(90deg);
-webkit-transform:rotate(90deg);
-ms-transform:rotate(90deg);


For the jquery I want to set a varable to check if the object has been rotated, then act accordingly.

I have been having a real difficult time trying to get it to work. I've put together a JsFiddle.

This is the code I am using:

var turn = true;
$("#button").click(function () {
$("#shape").css('transform', function(index) {
return index * 90;
});
});

Answer

Add some transitions and a rotate class, and just toggle that class:

css:

#shape  { width: 100px; 
          height: 200px; 
          background:#000;
          -moz-transition: all 1s ease;
          -webkit-transition: all 1s ease;
          -o-transition: all 1s ease;
           transition: all 1s ease;
         }

.rotate {-moz-transform: rotate(90deg);
         -webkit-transform:rotate(90deg); 
         -ms-transform:rotate(90deg);
         -o-transform:rotate(90deg);
         }

js:

$("#button").click(function() {
    $("#shape").toggleClass('rotate');
});‚Äč

FIDDLE

Comments