Monday, November 26, 2012

flip this

There are many jQuery libraries out there for generating a "Flip" transition effect, as if a card was flipping over.  Flip!'s page is polished, but the effect is marred by the content disappearing during the flip. (Also I didn't like how it encourages the back content to be generated programatically, rather than living with the rest of the content.) QuickFlip 2 does a better job keeping the content present, but the visual effect is rather lackluster. However I have found an excellent, easy to use library that has a high "hey, wow!" factor and only a few things to watch out for: Zachstronaut's rotate3Di. Here it is an action:

This is a trivial example, but the content inside can be any html, including images.

It took me a bit to wrap my head around how it works: it's some CSS transform magic with skewY() and scale() being animated in sync for the nifty 3D illusion. The front of the card/back of the card bit is really interesting: if you want different content for the front and back, you make a function for the sideChange parameter. This function is called halfway through the flip with a boolean argument that indicates if the front is showing. Your function is then responsible for show()ing the appropriate side and hide()ing the other (which makes sense: with a flat object, only one side is visible at a time... Amusingly, the defaults without this function are to show the content reversed.)

So for this example, I had this HTML:

<div class="flippable" id="flipExample">
    <div class="front">Click To Flip</div>
    <div class="back">The Back</div>
</div>

decorated with this CSS (some parts omitted for brevity, feel free to view source.)

.flippable {
    height:150px;
    width:150px;
    padding:1px;
}
.flippable .front {
    background-color:#ffcccc;
}
.flippable .back {
    display:none;
    background-color:#ccccff;
}

The code then was pretty easy...
$('#flipExample').click(
    function(){
        $(this).rotate3Di('toggle', 1000,
            {
                sideChange:function(isFront){
                    if(isFront) {$(this).find(".front").show();$(this).find(".back").hide();}
                    else  {$(this).find(".front").hide();$(this).find(".back").show();}
                }
            });
    }
);

So like I mentioned, the things to watch out for were pretty minor: one was that the container (which is what is actually being rotated, but maybe shouldn't have content of its own outside of what's in your front and back side content) needed 1 pixel of padding, otherwise some odd lines showed up during the animation in chrome. And also, you need to include 2 js files, not just 1: jquery-css-transform.js and rotate3Di.js. The Transform one is needed for IE9 tweaking, which brings us to IE in general: it doesn't work for IE8 or earlier, but it degrades gracefully into an untransitioned swap of the front with the back.

So, a nice effect, and easy to put into place.

No comments:

Post a Comment