Folding images v2.

Images fold-up when the are hovered!

by meetaaronsilber

HTML

<!-- Author: Aaron Silber -->

<!-- Insert your foldup images and give them the 'foldup' class -->
<img src="http://placekitten.com/200/200" class="foldup" />
<img src="http://placekitten.com/150/200" class="foldup" />

CSS

.foldwrap { 
    background: red;
    margin: 5px auto 15px;
}

div[class^="slice"] {
    -webkit-transition: all 200ms ease-in-out;
    -webkit-transform: perspective(0) rotatex(0) scale(1);
}

.foldwrap:hover div[class^="slice"]:nth-child(odd) {
    -webkit-transform-origin: 50% 0%;
    -webkit-transform: perspective(100) rotatex(20deg) scale(1, 0.5);
    margin-bottom: -40px; /* Corrects spacing between slices when transforms happen */
}

.foldwrap:hover div[class^="slice"]:nth-child(even) {
    -webkit-transform-origin: 50% 100%;
    -webkit-transform: perspective(100) rotatex(-20deg) scale(1, 0.5);
}

.foldwrap:hover div[class^="slice"]:nth-child(odd):before {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    background: rgba(200,200,200,0.2);
}

JavaScript

function FoldImg(islices) {
    
    var foldupsrc = $('.foldup');
    var folduph = foldupsrc.height();
    var foldupw = foldupsrc.width();
    
    function initSegments(i) {
        
        var thisimg = foldupsrc[i];
        var folduph = $(thisimg).height();
        var foldupw = $(thisimg).width();

        /* Create wrapper for this img's Segments */
        $(thisimg).before('<div class="foldwrap"></div>');
        var slicewrap = $(foldupsrc[i]).prev('.foldwrap');

        /* Given the foldwarp height and width based on src image h/w */
        $(slicewrap).css({"height":folduph,"width":foldupw});
        
        var foldupbg = $(foldupsrc[i]).attr('src');

        /* Create the basic slices for this image */
        for(i=0; i < islices; i++){
            e = i+1;
            var slicemarkup = $('<div style="background-image:url('+ foldupbg +')"></div>');
            $(slicewrap).append(slicemarkup.addClass('slice'+e));
        }
        
        foldupsrc.hide(); /* Remove src image */
    }
    
    function styleSegments() {
        $('.foldwrap').each( function() {
            var isegments = $(this).children().size(); /* Find the number of segments */

            var folduph = $(this).height();
            var foldupw = $(this).width();
            
            $(this).children().each( function(i) {
                $(this).css("height",(1/isegments*folduph));
                $(this).css("backgroundPositionY",(-i/isegments*folduph));
            });
        });
    }
    
    var imgs = foldupsrc.size();
    
    /* If browser supports transitions and such.. if modernizer used */
    if($('.csstransitions').length) {
        for(i=0; i < imgs; i++){
            initSegments(i);
        }
        styleSegments();
    }
}

$(document).ready(function(){
    FoldImg(5); /* Pass the number of slices */
});