How would I rotate an element with a jQuery's .animate()
? I'm using the line below, which is currently animating the opacity correctly, but does this support CSS3 transforms?
$(element).animate({ opacity: 0.25, MozTransform: 'rotate(-' + -amount + 'deg)', transform: 'rotate(' + -amount + 'deg)' });
The CSS rotate() function lets you rotate an element on a 2D axis. The rotate() function accepts one argument: the angle at which you want to rotate your web element. You can rotate an element clockwise or counter-clockwise.
As far as I know, basic animates can't animate non-numeric CSS properties.
I believe you could get this done using a step function and the appropriate css3 transform for the users browser. CSS3 transform is a bit tricky to cover all your browsers in (IE6 you need to use the Matrix filter, for instance).
EDIT: here's an example that works in webkit browsers (Chrome, Safari): http://jsfiddle.net/ryleyb/ERRmd/
If you wanted to support IE9 only, you could use transform
instead of -webkit-transform
, or -moz-transform
would support FireFox.
The trick used is to animate a CSS property we don't care about (text-indent
) and then use its value in a step function to do the rotation:
$('#foo').animate( .. step: function(now,fx) { $(this).css('-webkit-transform','rotate('+now+'deg)'); } ...
Ryley's answer is great, but I have text within the element. In order to rotate the text along with everything else, I used the border-spacing property instead of text-indent.
Also, to clarify a bit, in the element's style, set your initial value:
#foo { border-spacing: 0px; }
Then in the animate chunk, your final value:
$('#foo').animate({ borderSpacing: -90 }, { step: function(now,fx) { $(this).css('transform','rotate('+now+'deg)'); }, duration:'slow' },'linear');
In my case, it rotates 90 degrees counter-clockwise.
Here is the live demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With