Reputation: 253
I've got the following keyframe animation,
@-webkit-keyframes rotate {
from {
-webkit-transform: rotateY(0);
-moz-transform: rotateY(0);
transform: rotateY(0);
}
to {
-webkit-transform: rotateX(2160deg);
-moz-transform: rotateX(2160deg);
transform: rotateX(2160deg);
}
}
Now under a certain condition, I'd like to change the to {}
part of this animation, and then the rotation.
I'd like to achieve this using .css
(?). How would I do this without using multiple animation, but just change the CSS instead?
Upvotes: 2
Views: 58
Reputation: 14313
.css
doesn't support -webkit-keyframes
that way. However, you can generate a new WebKit keyframe on the fly by appending a style
tag. In this code I used JavaScript's multi-line quote character ` (lowercase tilde).
var uniqueRotate = 0;
$('#test').click(function () {
var amountToRotate = Math.floor(180 * Math.random()) + 'deg',
myRotateId = 'rotate' + uniqueRotate++;
$('<style>')
.text(`
@-webkit-keyframes ` + myRotateId + ` {
from {
-webkit-transform: rotateY(0);
-moz-transform: rotateY(0);
transform: rotateY(0);
}
to {
-webkit-transform: rotateX(` + amountToRotate + `);
-moz-transform: rotateX(` + amountToRotate + `);
transform: rotateX(` + amountToRotate + `);
}
}
`)
.appendTo(document.body);
$(this).css('animation', '1s ease-out 0s 1 ' + myRotateId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<div id='test'>Testing cool stuff! Please click me!</div>
var uniqueRotate = 0;
$('#test').click(function () {
var amountToRotate = 180 * Math.random(),
animationTime = 2*1000,
updatePerMs = 20,
iterations = 0; // every 20 ms we update our timer
var myTimer = setInterval(function () {
iterations++;
var ratio = (updatePerMs*iterations) / animationTime,
current = Math.floor(ratio * amountToRotate);
if (ratio > 1) {
clearInterval(myTimer);
return;
}
$(this).css({
'-webkit-transform': 'rotateX(' + current + 'deg)',
'-moz-transform': 'rotateX(' + current + 'deg)',
'transform': 'rotateX(' + current + 'deg)'
});
}.bind(this), updatePerMs);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<div id='test'>Testing cool stuff! Please click me!</div>
Upvotes: 1