TDG TDG - 1 year ago 31
jQuery Question

Rotate only this div.. not others

Want to rotate div 45 degree on each click. It works fine as expected. I have 3 '.expand-btn' class name in this page. What happens, on click it triggers on all '.expand-btn'.

I want to trigger only on this 'expand-btn'. not others.

JS:

var _rotation = 0;

$.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};

$('.expand-btn').click(function() {
_rotation += 45;
$(this).rotate(_rotation);
});


HTML:

<div class="expand-btn" id="test1">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test2">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>
<div class="expand-btn" id="test3">
<a href="javascript:void(0);" data-toggle="collapse">+</a>
</div>

Answer Source

You would need to have a distinct storage of the rotation value for each of the objects. You could e.g. use jQuery.data() for that:

$.fn.rotate = function(delta) {
   // get the current stored rotation, or 0 if none was currently stored
   var degrees = $(this).data().rotation || 0;

   // add the delta to this value
   degrees += delta;

   // store the new value with the object
   $(this).data().rotation = degrees;

   // set the transformation
   $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};

$('.expand-btn').click(function() {
    $(this).rotate(45);
});

To extend a jQuery set correctly you should iterate over the elements of the set and apply the code for each of the individually. The way $.fn.rotate is written now will set the rotation of all elements in the set based on the value of the first one.

Or parse the current transform to retrieve that actual value.

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