jQuery: how do I animate a div rotation?

Make use of WebkitTransform / -moz-transform: rotate(Xdeg). This will not work in IE, but Matt’s zachstronaut solution doesn’t work in IE either.

If you want to support IE too, you’ll have to look into using a canvas like I believe Raphael does.

Here is a simple jQuery snippet that rotates the elements in a jQuery object. Rotation can be started and stopped:

$(function() {
    var $elie = $("img"), degree = 0, timer;
    rotate();
    function rotate() {
        
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});                      
        timer = setTimeout(function() {
            ++degree; rotate();
        },5);
    }
    
    $("input").toggle(function() {
        clearTimeout(timer);
    }, function() {
        rotate();
    });
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<input type="button" value=" Toggle Spin " />
<br/><br/><br/><br/>
<img src="http://i.imgur.com/ABktns.jpg" />

Leave a Comment