Reputation: 189
I would like to rotate an image 180 degrees when it is clicked. Then rotate that same image a further 180 degrees (completing the revolution) on subsequent click.
I have achieved the first part using:
.img_rotator_180 {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-o-transform: rotate(180deg);
-ms-transform: rotate(180deg);
}
.img_rotator_360 {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-o-transform: rotate(180deg);
-ms-transform: rotate(180deg);
}
.img_rotator_transition {
-webkit-transition: all 1s ease-out; /* Chrome 1-25, Safari 3.2+ */
-moz-transition: all 1s ease-out; /* Firefox 4-15 */
-o-transition: all 1s ease-out; /* Opera 10.50–12.00 */
transition: all 1s ease-out; /* Chrome 26, Firefox 16+, IE 10+, Opera 12.50+
}
And
$('div.' + this.id + ' img').addClass('img_rotator_180 img_rotator_transition');
Alternative version:
$('div.' + this.id + ' img').addClass('img_rotator_180 img_rotator_transition');
What happens with this is that the images initial rotation is not remembered meaning that the second rotation effectively redoes the 180 degree rotation.
Is there a way to establish the images current rotation before applying further transformation? Or perhaps a way to append rotation rather than replace it?
Thank you
Upvotes: 0
Views: 162
Reputation: 71230
HTML
<div>Click Me!</div>
jQuery
$('div').on('click', function () {
if ($(this).hasClass('spinIn')) {
$(this).addClass('spinOut').removeClass('spinIn');
} else {
$(this).addClass('spinIn').removeClass('spinOut');
}
});
CSS
div {
display:inline-block;
}
.spinIn {
-webkit-animation: spinIn 0.6s 1 linear;
animation: spinIn 0.6s 1 linear;
-webkit-animation-fill-mode:forwards;
animation-fill-mode:forwards;
}
@-webkit-keyframes spinIn {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(180deg);
}
}
@keyframes spinIn {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(180deg);
}
}
.spinOut {
-webkit-animation: spinOut 0.6s 1 linear;
animation: spinOut 0.6s 1 linear;
-webkit-animation-fill-mode:forwards;
animation-fill-mode:forwards;
}
@-webkit-keyframes spinOut {
0% {
-webkit-transform: rotate(180deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spinOut {
0% {
transform: rotate(180deg);
}
100% {
transform: rotate(360deg);
}
}
Upvotes: 1