How to rotate a div using jQuery

Is it possible to rotate a div using jQuery? I can rotate the image, but I can not rotate the div; is there any solution for this?

+45
jquery
Jun 11 '10 at 7:21
source share
1 answer

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 special conversions will be added automatically. jsFiddle Demo

var rotation = 0; jQuery.fn.rotate = function(degrees) { $(this).css({'transform' : 'rotate('+ degrees +'deg)'}); return $(this); }; $('.rotate').click(function() { rotation += 5; $(this).rotate(rotation); }); 



EDIT: Added code to make it a jQuery function.

For those of you who do not want to read further, you are here. For more information and examples, read on. jsFiddle Demo .

 var rotation = 0; jQuery.fn.rotate = function(degrees) { $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)', '-moz-transform' : 'rotate('+ degrees +'deg)', '-ms-transform' : 'rotate('+ degrees +'deg)', 'transform' : 'rotate('+ degrees +'deg)'}); return $(this); }; $('.rotate').click(function() { rotation += 5; $(this).rotate(rotation); }); 



EDIT: One of the comments on this post is mentioned by jQuery Multirotation . This jQuery plugin essentially performs the above function with IE8 support. It might be worth using if you want to have maximum compatibility or more options. But for minimal overhead, I suggest this feature. It will work on IE9 +, Chrome, Firefox, Opera and many others.




Bobby ... This is for people who really want to do this in javascript. This may be required to rotate on a javascript callback.

Here is jsFiddle .

If you want to rotate at custom intervals, you can use jQuery to manually install css instead of adding a class. Like this one ! I have included both jQuery options at the bottom of the answer.

HTML

 <div class="rotate"> <h1>Rotatey text</h1> </div> 

CSS

 /* Totally for style */ .rotate { background: #F02311; color: #FFF; width: 200px; height: 200px; text-align: center; font: normal 1em Arial; position: relative; top: 50px; left: 50px; } /* The real code */ .rotated { -webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */ -moz-transform: rotate(45deg); /* Firefox 3.5-15 */ -ms-transform: rotate(45deg); /* IE 9 */ -o-transform: rotate(45deg); /* Opera 10.50-12.00 */ transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */ } 

JQuery

Make sure they are wrapped in $ (document) .ready

 $('.rotate').click(function() { $(this).toggleClass('rotated'); }); 

User Intervals

 var rotation = 0; $('.rotate').click(function() { rotation += 5; $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)', '-moz-transform' : 'rotate('+ rotation +'deg)', '-ms-transform' : 'rotate('+ rotation +'deg)', 'transform' : 'rotate('+ rotation +'deg)'}); }); 
+66
Jun 27 '13 at 16:40
source share



All Articles