okainov
okainov

Reputation: 4654

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

JS:

$(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.

Upvotes: 0

Views: 438

Answers (2)

Joseph
Joseph

Reputation: 1041

Here is your code fixed.

    $(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
      });
    });

Markup:

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

Upvotes: 1

Dave
Dave

Reputation: 2900

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

UPDATED

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());
    
    //restore
    if(currentDeg > 270){
      $(this).attr("data-deg", "0");
    }
    
  });
});
.rotating {
  width: 20px;
  height: 20px;
  background-color: red;
  margin-top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rotating" data-deg="90">A</div>
<div class="rotating" data-deg="90">A</div>

Upvotes: 1

Related Questions