sam
sam

Reputation: 10064

'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;
    });
});

Upvotes: 1

Views: 4914

Answers (3)

pim
pim

Reputation: 12577

I think in general, if you're going to use transition's you should target the specific properties you want to affect. I would consider the use of "all" to be poor practice.

Target alternative: css:

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

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

///jquery

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

Upvotes: 0

adeneo
adeneo

Reputation: 318182

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

Upvotes: 10

Pavel Staselun
Pavel Staselun

Reputation: 2010

If I understood correct, THIS should do it.

Upvotes: 2

Related Questions