SB2055
SB2055

Reputation: 12892

Reversing an animation with CSS

I'm applying a mixin to rotate something by adding the class via jQuery:

.rotate-45-left() {
    -webkit-animation: rotate45left 2.55s ease;
    -moz-animation: rotate45left 2.55s ease;
    animation: rotate45left 2.55s ease;
    animation-fill-mode: forwards;
}
@keyframes rotate45left {
    100% {
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
    }
}

This works the first time, however I'd like to then animate the transition back to its default, unrotated position. I've tried adding an additional class but this overrides the original animation; removing the class resets it without animating. Is there a simple way to achieve this?

Upvotes: 0

Views: 42

Answers (1)

Yogen Darji
Yogen Darji

Reputation: 3300

function back(){
document.getElementById('ele').classList = "rotate-0-left";
}
.rotate-45-left {
    -webkit-animation: rotate45left 1.55s ease;
    -moz-animation: rotate45left 1.55s ease;
    animation: rotate45left 1.55s ease;
    animation-fill-mode: forwards;
}

.rotate-0-left {
    -webkit-animation: rotate0left 1.55s ease;
    -moz-animation: rotate0left 1.55s ease;
    animation: rotate0left 1.55s ease;
    animation-fill-mode: forwards;
}

@keyframes rotate45left {
    
    100%{
     -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
    }
}


@keyframes rotate0left {
   0%{
   -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
    }
   }
    100%{
     -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
}
<h1 id="ele" class="rotate-45-left"> Rotate </h1>

<input type="button" value="back to original" onClick="back()"/>

Upvotes: 1

Related Questions