user3654727
user3654727

Reputation: 13

CSS3 Transform only plays first item

I am trying to get my div to rotate 360deg every time I click it, using CSS3 transform rotate. However, I'm also using the CSS3 transform translate to vertically align my div.

On the first click, it applies all the required CSS but doesn't actually rotate, however will rotate all clicks after that. It stays vertically aligned the whole time.

Unsure how to solve this and any help is appreciated :)

My css:

    #my-div {
        height: 300px;
        width: 300px;
        transition: all 0.5s ease-in-out;
        display: block;
        margin: auto;

        /*to vertically align*/
        position: relative;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
    }

My javascript

var angle = 360
        $('#my-div').click(function() {
            $(this).css({
                '-webkit-transform' : 'translateY(-50%) rotate('+angle+'deg) ',
                'transform' : 'translateY(-50%) rotate('+angle+'deg)'
            })
            angle += 360
        });

Upvotes: 1

Views: 117

Answers (1)

King King
King King

Reputation: 63387

In fact the transition works properly only when the 2 ends are explicitly set, here intially the rotate transform is not set explicitly, after the first click, it's explicitly set to rotate(360deg) and hence the next clicks work. To solve this, you just need to apply rotate(0deg) for your div initially via the CSS code:

#my-div {
   /*...*/
   -webkit-transform: translateY(-50%) rotate(0deg);
    transform: translateY(-50%) rotate(0deg);
}

Note that I emphasized on the properly word, in fact if you set the initial angle to some angle equal or smaller than 180deg, you'll see it transitions OK. I doubt that if you don't set the initial rotate transform explicitly, the behavior is determined by the browser, that is 360deg won't make any transition, otherwise the rotating transition may be clockwise (if the angle % 360 is less than or equal to 180deg) and counter-clockwise if the angle % 360 is greater than 180deg (note about the modulo operation between angle and 360).

Demo.

Upvotes: 1

Related Questions