Search code examples
javascriptcssanimationrotationtransition

What is the simplest way to rotate a div smooth?


What is the best way to make a div rotate on click, but with a transition?

I tried this but it only makes a smooth transition when class is added but not when class is removed :

js :

$('#firstDiv' + id).click(function(){
    $("#Img" + id).toggleClass('rotated');
});

css :

.rotated { 
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -webkit-transition: all 0.1s linear;
}

Solution

  • transition css property should stay on the element.

    transition property is what makes makes the rotation look smooth. When it's on the class which is doing the rotation and you remove the class, even the transition property gets removed. Hence the rotation end is not smooth.

    Your logic is right but use may be a different class to apply -webkit-transition: all 0.1s linear; or apply directly on the element. Make sure it is not removed when you remove rotated class.

    const myDiv = $('#my-div');
    
    setTimeout(()=>{
      myDiv.addClass('rotated');
    }, 1000);
    div {
      width: 100px;
      height: 100px;
      background-color: red;
      transition: all 1s linear;
    }
    
    .rotated { 
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
        -o-transform: rotate(-90deg);
        -ms-transform: rotate(-90deg);
        transform: rotate(-90deg);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id='my-div'>
    </div>