The Godfather The Godfather - 2 years ago 73
CSS Question

Several rotating divs using Javascript

I need to have several divs and each of them should be able to rotate in four(!) directions independently by mouse click.

From this question (and some other) I've found pretty suitable way to rotate in 4 directions (not in two which is much easier)
Rotate a div using javascript, here is the fiddle


$(document).ready(function() {
var degree = 0; //Current rotation angle, 0->0, 1->90, 2->180, 3->270
$('.rotating').click(function() {
$(this).toggleClass('rotated' + degree.toString()); //Disable previous rotation
degree = (degree + 1) % 4;
$(this).toggleClass('rotated' + degree.toString()); //Add new rotation

But it works well only for one rotating element. As soon as I add the second div, it stops working as expected (rotations are not independent, try to click on "A" first and then on "B")

<div class="rotating rotated0">A</div>
<div class="rotating rotated0">B</div>

I assume, the root cause is because I use one "degree" variable and it's shared between my divs. So, that's the question - how can I implement several divs which can be rotated independently?

I've updated the code according to first answers (changed id to class), but initial issue with independence is still in place.

Answer Source

id attribute must be only one. Change id into class.


Here is final code:

$(document).ready(function() {
  $('.rotating').click(function() {
    var currentDeg   =  $(this).attr("data-deg");
    $(this).css({ '-moz-transform': 'rotate(' + currentDeg + 'deg)'});
    $(this).css({ WebkitTransform: 'rotate(' + currentDeg + 'deg)'});
    currentDeg = eval(currentDeg)+eval(90);
    $(this).attr("data-deg", currentDeg.toString());
    if(currentDeg > 270){
      $(this).attr("data-deg", "0");
.rotating {
  width: 20px;
  height: 20px;
  background-color: red;
  margin-top: 0px;
<script src=""></script>
<div class="rotating" data-deg="90">A</div>
<div class="rotating" data-deg="90">A</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download