jQuery rotate/transform

Andrea picture Andrea · Oct 29, 2011 · Viewed 132.4k times · Source

I'd like to use this function to rotate then stop at a particular point or degree. Right now the element just rotates without stopping. Here's the code:

    <script type="text/javascript">
    $(function() {
       var $elie = $("#bkgimg");
       rotate(0);
       function rotate(degree) {

           // For webkit browsers: e.g. Chrome
           $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
           // For Mozilla browser: e.g. Firefox
           $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

           // Animate rotation with a recursive call
           setTimeout(function() { rotate(++degree); },65);
       }
    });
    </script>

Thanks for your help

Answer

Sparky picture Sparky · Oct 29, 2011

Simply remove the line that rotates it one degree at a time and calls the script forever.

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Then pass the desired value into the function... in this example 45 for 45 degrees.

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
      // For webkit browsers: e.g. Chrome
           $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
           $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
        }

});

Change .css() to .animate() in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
            $elie.animate({
                        '-webkit-transform': 'rotate(' + degree + 'deg)',
                        '-moz-transform': 'rotate(' + degree + 'deg)',
                        '-ms-transform': 'rotate(' + degree + 'deg)',
                        '-o-transform': 'rotate(' + degree + 'deg)',
                        'transform': 'rotate(' + degree + 'deg)',
                        'zoom': 1
            }, 5000);
        }
});

EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate() does not yet support the CSS3 transforms.

This jQuery plugin is supposed to animate the rotation:

http://plugins.jquery.com/project/QTransform