0

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";
});

2 Answers 2

4

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.