Search code examples
javascriptcssrotationtransformtransition

CSS transform rotate in the same direction each time


I'm wanting to make an element on a web page rotate 360 degrees anticlockwise each time a button is clicked. I've found some example code showing how to do this but the only issue is that currently it rotates in alternating directions.

Is there a simple way to ensure that the element rotates in the same direction every time?

$('button').click(function() {
  $('.box').toggleClass('box-rotate');
});
.box {
  background: lightblue;
  width: 200px;
  height: 200px;
  margin: 20px auto;
  transition: transform 1s linear;
  transform-origin: top left;
  transform-style: preserve-3D;
}

.box-rotate {
  transform: rotate(360deg);
}

button {
  display: block;
  margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="box"></div>
<button>click me</button>

View on CodePen


Solution

  • Your example adds and removes the class that applies the transformation, which has the effect of applying the transformation when the class is added, and then undoing it when the class is removed, hence the reversal of the rotation on the second click.

    To increment the rotation each time, you could use JavaScript to keep count of the current rotation value and increment it when the button is clicked, I've forked your example on CodePen here: http://codepen.io/anon/pen/aObMYK to illustrate. Note that I've changed the increment to 30 degrees so you can see what's going on more clearly. If you want to have it as 360 degree rotation each time, just change the value set in counter += 30; to 360.

    var counter = 0;
    $('button').click(function() {
      counter += 30;
      $('.box').css('transform', 'rotate(' + counter + 'deg)')
    });
    .box {
      background: lightblue;
      width: 200px;
      height: 200px;
      margin: 20px auto;
      transition: transform 1s linear;
      transform-origin: top left;
      transform-style: preserve-3D;
    }
    
    button {
      display: block;
      margin: auto;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
    <div class="box"></div>
    <button>click me</button>