0

I found this link on how to rotate a div using JQuery.

Rotating a Div Element in jQuery and some more articles too.

The code is as follows

    $(function() {
            var $elie = $("#wheel");
            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)'
                });
                $elie.css({
                    '-ms-transform' : 'rotate(' + degree + 'deg)'
                });

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

        });

Could someone please help me to extend this code to Rotating an element clockwise and anticlockwise randomly like a steering wheel

Community
  • 1
  • 1
Mr.Zero to Hero
  • 65
  • 2
  • 10
  • You need to use math.random on the degree so that it can choose negative or positive. – Cam May 09 '13 at 15:01

2 Answers2

4

you can extend jQuery.animate() to create something like this jsfiddle

$.fx.step['degree']=function(fx){
if(! fx.deg){
    fx.deg=0;
    if($(fx.elem).data("degree")){
        fx.deg=$(fx.elem).data("degree")
    }   
}
$(fx.elem).css({"WebkitTransform":"rotate("+Math.floor(fx.deg+(fx.end*fx.pos))+"deg)","-moz-transform":"rotate("+Math.floor(fx.deg+(fx.end*fx.pos))+"deg)","-ms-transform":"rotate("+Math.floor(fx.deg+(fx.end*fx.pos))+"deg)"});
$(fx.elem).data("degree",Math.floor(fx.deg+(fx.end*fx.pos)));    }
Abraham Uribe
  • 3,118
  • 7
  • 26
  • 34
  • you're welcome you can change it to work without .data() but the css transforms look like transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0) – Abraham Uribe May 09 '13 at 16:06
2

you just have to change the code inside the setTimeout to make the increment/decrement random

 // Animate rotation with a recursive call
                setTimeout(function() {
                    increment= Math.random() < 0.5 ? -1 : 1;
                    degree+=increment;
                    rotate(degree);
                }, 5);

or

increment = Math.floor(Math.random()*3)-1;

for -1,0,1 movements

Borgtex
  • 3,235
  • 1
  • 19
  • 28