Reputation: 25
I want to rotate this div on click, when it's clicked it had to stay in the rotated state(45deg). but when you click again it will go back to the original rotation(0deg).
This is my code right now, maybe someone can help me!?
JSFIDDLE:
https://jsfiddle.net/sz2yfr51/2/
CODE:
var boxopen = document.getElementById('boxopen');
boxopen.addEventListener("click", function(){
boxopen.style.animation = "rotate 2s";
boxopen.style.webkitAnimation = "rotate 2s";
});
Upvotes: 0
Views: 84
Reputation: 3410
All you have to do is to maintain the state using a variable and reverse the animation for that state.
Also add the animation-fill-mode : forwards;
for allowing the object to settle in final keyframe state.
The following code can be used to reverse the rotation you provided.
@keyframes rotateback {
0% {
-moz-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
100% {
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
}
Check out this fiddle: https://jsfiddle.net/t60Lsmqj/
Upvotes: 0
Reputation: 1279
You can use style.transform and style.transition:
var boxopen = document.getElementById('boxopen');
var rotate = 0;
boxopen.addEventListener("click", function(){
rotate = rotate ? 0 : 45;
boxopen.style.transform = "rotate(" + rotate + "deg)";
boxopen.style.transition = "transform 2s";
});
https://jsfiddle.net/sz2yfr51/8/
Upvotes: 4