I'm trying to rotate any .test
div clockwise by 180˚ each time it is clicked.
What I have done is essentially:
- If no rotation has occurred, rotate to 180˚.
- If it's been rotated to 180˚, rotate to 360˚.
- If it's been rotated to 360˚, remove
transform
andtransition
properties and rotate to 180˚.
$(".test").click(function(){
var angle;
var matrix = $(this).css("-webkit-transform")
if (matrix == "none") { //div hasn't been rotated yet
angle = 0;
}
else {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0]; //should be -1 if div is upside down, 1 if it is normal.
if(a == 1) {
$(this).removeAttr('style');
angle = 0;
}
else {
angle = 180;
}
}
$(this).css({
"-webkit-transform": "rotate("+(angle+180)+"deg)",
"-moz-transform": "rotate("+(angle+180)+"deg)",
"transform": "rotate("+(angle+180)+"deg)",
"-webkit-transition": "-webkit-transform 0.3s ease-in",
});
});
This works fine for first two clicks, but on the third click, the div rotates counterclockwise, as if it's rotating from 360˚ to 180˚, despite the fact that I've already removed the style
attribute.
Here's a working fiddle: https://jsfiddle.net/wwny5q5d/3/
Now, the thing that's got me really curious is that if I add an alert
or debugger
before calling .css()
, the third rotation goes as I want it to, clockwise.
alert("Now it will always rotate clockwise")
$(this).css({
"-webkit-transform": "rotate("+(angle+180)+"deg)",
"-moz-transform": "rotate("+(angle+180)+"deg)",
"transform": "rotate("+(angle+180)+"deg)",
"-webkit-transition": "-webkit-transform 0.3s ease-in",
});
So my questions are: Why doesn't my div rotate clockwise on the third click, AND why does the inclusion of the alert
make it work?