Last active
August 29, 2015 14:18
-
-
Save nmyers/b9d5fa4989cb2df4f019 to your computer and use it in GitHub Desktop.
Fuidbricks - basic masonry alternative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Requires imagesLoaded | |
* | |
*/ | |
(function($) { | |
$.fluidbricks = function(element, options) { | |
var defaults = { | |
'itemClass': '.element', | |
'columnWidth': 60 | |
}; | |
var settings = $.extend({}, defaults, options); | |
var $element = $(element); | |
var n_columns = 1; | |
var _fbr = this; | |
var $children = $(settings.itemClass,element); | |
var children_list = $children.detach(); | |
$.extend(_fbr, { | |
refresh: function() { | |
n_columns = 0; // to force a relayout | |
_fbr.resize(); | |
}, | |
resize: function() { | |
var element_width = $element.width(); | |
var item_width = $(settings.columnWidth).width(); | |
var new_n_columns = Math.round(element_width/item_width); | |
if (new_n_columns != n_columns) { | |
$('.col',element).remove(); | |
n_columns = new_n_columns; | |
for (var i = 0; i < n_columns; i++) { | |
$element.append('<div class="col col-'+(i+1)+'-of-'+n_columns+'" ></div>'); | |
} | |
$('.col').eq(Math.floor(n_columns/2)).append('<div class="l-ratio" ></div>'); | |
var cur_column_index = 0; | |
var avg_height = 0; | |
$.each(children_list,function(index,val) { | |
var $col = $('.col',element).eq(cur_column_index); | |
if ($(this).hasClass('hide')) { | |
$col.append(this); | |
return true; | |
} | |
var avg_height = 0; | |
$('.col',element).each(function(index,val){ | |
avg_height += $(this).height(); | |
}); | |
avg_height = avg_height / n_columns; | |
while ($col.height()>avg_height) { | |
cur_column_index = ++cur_column_index % n_columns; | |
$col = $('.col',element).eq(cur_column_index); | |
} | |
$col.append(this); | |
cur_column_index = ++cur_column_index % n_columns; | |
}); | |
} | |
} | |
}); | |
$element.imagesLoaded( function() { | |
$(window).resize(throttle(function(event) {_fbr.resize();},400)); | |
_fbr.resize(); | |
$element.addClass('fbr-loaded'); | |
}); | |
}; | |
$.fn.fluidbricks = function(options) { | |
if ( typeof options == 'string') { | |
var instance = $(this).data('fluidbricks'); | |
var args = Array.prototype.slice.call(arguments, 1); | |
if ( instance[options] ) | |
return instance[options].apply(instance, args); | |
return; | |
} else { | |
return this.each(function() { | |
if (undefined === $(this).data('fluidbricks')) { | |
var plugin = new $.fluidbricks(this, options); | |
$(this).data('fluidbricks', plugin); | |
} | |
}); | |
} | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment