views:

173

answers:

2

I'm trying to make a box rotate through javascript/css3 rotate every time I click on it. It works, but only the first time I click on it. Each time after, I get the alert which means it's not a javascript error - but no animation.

Here is my simple page -

<script>
  function rotate( box )
  {
    alert('start');
    box.style.webkitTransform = 'rotate(360deg)';
  }
</script>

<style>
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; }
</style>

<div id='box' onclick='rotate(this);'></div>

I figured there needs to be something I need to put after the rotate() to tell it to go back to the beginning stage so that it can rotate 360 again.

+1  A: 

I reuse a script i made previously. It should now support Mozilla too.

<!-- head part -->
<script type="text/javascript">
var angle   = 0;    //Current rotation angle 
var nbSteps = 30;   //More steps is more fluid
var speed   = 1000; //Time to make one rotation (ms)
var count   = 0;    //Count the nb of movement (0..nbSteps-1)
var element = null;

/**
 * Rotate the element passed
 */
function rotate(box) {
    if(count == 0) {
        element = box;
        rotateLoop();
    }
}

/**
 * Recursive method that rotate step by step
 */
function rotateLoop() {
    angle-=360/nbSteps;

    setElementAngle(angle);
    count++;

    if(count < nbSteps) {
        setTimeout("rotateLoop()",speed/nbSteps);
    }
    else {
        count=0;
        setElementAngle(0); //Just to be sure
    }
}

/**
 * Use for the rotation
 */
function setElementAngle(angle) {
    var rotationStyle = "rotate(" + (360-angle) + "deg)";
    element.style.WebkitTransform = rotationStyle;
    element.style.MozTransform = rotationStyle;
    element.style.OTransform = rotationStyle;
}
</script>

<style>
#box{
    height:100px;
    width:100px; 
    border:1px solid red;
    }
</style>

<!-- body part -->
<div id='box' onclick="rotate(this);"></div>
h3xStream
+1  A: 

Edit: Assuming you want it to be completely CSS:

Webkit transitions are currently being tested and are very rough. Especially for what you want to do. Since these are "transformations", and the style string is quite complex, it creates a nasty challenge.

The best thing to do it to reverse the rotation every other click:

<script>
function rotate( box )
{
  box.style.webkitTransform = box.style.webkitTransform == "rotate(360deg)" ? "rotate(0deg)" : "rotate(360deg)";
}
</script>

<style>
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; }
</style>

<div id='box' onclick='rotate(this);'></div>

Or youll have to deal with alot of dangerous coding, or javascript alternatives.

digitalFresh
This solution will rotate the square in the opposite side the second time.I would add the support for Mozilla with the MozTransform property and maybe add a extra variable to avoid click event while it's already in rotation.
h3xStream