How to flip a div with JQuery and CSS3 animation<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to flip a div with JQuery and CSS3 animation

Posted on: July 11, 2013

If you are curious about what we will discuss in this blog post, you can visit JsFiddle for the code and an example of how to flip a div with CSS3 and some javascript.

First of all, here is the Html markup which define two divisions which are each side. Both side contain a text. When using the button, it goes from one div to the other with an animation that flip the division. The goal is to simulate that the user click some where and we go behind a div.

1<section id="zone">
2 <div class="recto"> Patrick </div>
3 <div class="verso" style="display:none"> Desjardins </div>
4 <button id="btnFlip">Flip</button>

The second step is to define a style to all those Html markup. It also defines the animation that we use to make it looks like if we were flipping the div to go behind it.


1#zone div {
2 width:150px;
3 height:150px;
4 background-color:yellow;
5 color:black; font-size:18px;
6 }
8 #zone {
9 -webkit-perspective: 1200px;
10 }
12 @-webkit-keyframes spinner {
13 from {
14 -webkit-transform: rotateY(0deg);
15 }
16 to {
17 -webkit-transform: rotateY(-180deg);
18 }
19 }
21.flip {
22 -webkit-animation-name: spinner;
23 -webkit-animation-timing-function: linear;
24 -webkit-animation-iteration-count: 1;
25 -webkit-animation-duration: 1s;
26 -webkit-transform-style: preserve-3d;
27 -webkit-transform-origin:50% 50%;

The first selector (#zone div) define the final state of both division. This is required because we want to be able to flip something similar. Also, we will be able to flip back to the original state. Nonetheless, we define a perspective for the zone which will create during the animation a sense of depth. Finally, we specify an animation key frames which do a 3d transformation by using the CSS3 features called rotateY. This will create a flip at the Y axis. Also, the class "flip" is defined which specify where the rotation occur (in the middle of the div) and also the duration which is 1 second in this example.

The last step is to define the action on the button. This action could have been placed directly onto the div but to not mix concept here, we will attach a click event to a button.

1$(document).on("click", "#btnFlip", function flipDiv() {
2 $('#zone div:hidden').removeClass('flip')
3 $('#zone div:visible').addClass('flip')
4 .delay(600)
5 .fadeOut(300, function(){
6 $('#zone div:not(.flip)').fadeIn(300)});

What are we doing here is that we remove from the hidden div the "flip" class and add it to the other division. This let us having a continual movement of the class "flip" between the front and the back.