public
Created

  • Download Gist
jquery.sliced.css
CSS
1 2 3 4 5 6
.sliced {
position: relative;
width: 640px;
height: 400px;
}
.tile { float: left; }
jquery.sliced.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
;(function( $, window ) {
 
var _defaults = {
x : 2, // number of tiles in x axis
y : 2, // number of tiles in y axis
random : true, // animate tiles in random order
speed : 2000 // time to clear all times
};
 
/**
* range Get an array of numbers within a range
* @param min {number} Lowest number in array
* @param max {number} Highest number in array
* @param rand {bool} Shuffle array
* @return {array}
*/
function range( min, max, rand ) {
var arr = ( new Array( ++max - min ) )
.join('.').split('.')
.map(function( v,i ){ return min + i });
return rand
? arr.map(function( v ) { return [ Math.random(), v ] })
.sort().map(function( v ) { return v[ 1 ] })
: arr;
}
 
$.fn.sliced = function( options ) {
 
var o = $.extend( {}, _defaults, options );
 
return this.each(function() {
var $container = $(this);
 
/*---------------------------------
* Make the tiles:
---------------------------------*/
 
var width = $container.width(),
height = $container.height(),
$img = $container.find('img'),
n_tiles = o.x * o.y,
tiles = [], $tiles;
 
for ( var i = 0; i < n_tiles; i++ ) {
tiles.push('<div class="tile"/>');
}
 
$tiles = $( tiles.join('') );
 
// Hide original image and insert tiles in DOM
$img.hide().after( $tiles );
 
// Set background
$tiles.css({
width: width / o.x,
height: height / o.y,
backgroundImage: 'url('+ $img.attr('src') +')'
});
// Adjust position
$tiles.each(function() {
var pos = $(this).position();
$(this).css( 'backgroundPosition', -pos.left +'px '+ -pos.top +'px' );
});
/*---------------------------------
* Animate the tiles:
---------------------------------*/
 
var tilesArr = range( 0, n_tiles, o.random ),
tileSpeed = o.speed / n_tiles; // time to clear a single tile
tilesArr.forEach(function( tile, i ) {
setTimeout(function(){
$tiles.eq( tile ).fadeTo( 'fast', 0 );
}, i * tileSpeed );
});
 
});
 
};
 
}( jQuery, window ));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.