1

I'd like a button to rotate an element 5 additional degrees each time it's clicked. I've been able to do this sort of thing with border width with something like

  $(document).on('click', '.brdr_width_up', function() {
        $(ws.currentCell).css({'border-top-width' : '+=1', 'border-right-width' : '+=1','border-bottom-width' : '+=1','border-left-width' : '+=1'});
 });

But the same idea doesn't seem to work with transform:rotate:

    $(document).on('click', '.rotate_cw', function() {
        $(ws.currentCell).css({'-webkit-transform': 'rotate(+=5deg)'});
        $(ws.currentCell).css({'-moz-transform': 'rotate(+=5deg)'});
        var deg = $(ws.currentCell).css({'-moz-transform': 'rotate()'});
     });

And the var line above doesn't bring back the current rotation so that I could add to it.

Does anyone know a way to do this?

Thanks

Steve
  • 4,534
  • 9
  • 52
  • 110

2 Answers2

5

If you don't want to be messing around with the matrix, you can just use a data attribute to keep track of the rotation, and do something more like this:

$(document).on('click', '.rotate_cw', function() {
    var r = $(ws.currentCell).data('rot') + 5;
    $(ws.currentCell).css({
      '-webkit-transform': 'rotate('+r+'deg)',
         '-moz-transform': 'rotate('+r+'deg)',
          '-ms-transform': 'rotate('+r+'deg)',
           '-o-transform': 'rotate('+r+'deg)',
              'transform': 'rotate('+r+'deg)'
    }).data('rot', r);
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

Use the following function (source: Get element -moz-transform:rotate value in jQuery)

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return angle;
}

To get the rotation and then add 5 degrees to the angle and reapply, e.g.

$(document).on('click', '.rotate_cw', function() {
   var target = $(ws.currentCell);
   var rotation = getRotationDegrees(target) + 5;
   target.css({
      '-webkit-transform': 'rotate(' + rotation + 'deg)'
   ,  '-moz-transform': 'rotate(' + rotation + 'deg)'
   ,  '-o-transform': 'rotate(' + rotation + 'deg)'
   ,  '-ms-transform': 'rotate(' + rotation + 'deg)'
   ,  'transform': 'rotate(' + rotation + 'deg)'
   });
});

This also works for elements that have a default rotation applied.

jsFiddle: http://jsfiddle.net/georeith/px8fL/7/

Community
  • 1
  • 1
George Reith
  • 13,132
  • 18
  • 79
  • 148