Browse Source

Added option to center items horizontally

When the layout mode fitRows is set and the option fitRows.centered is set to "true", items not spanning the whole container will be centered within the container. I tried adding this functionality to the masonry layoutmode, but failed miserably. In retrospect this was pretty easy, but it took me quite some time to understand how isotope and it's layout modes work internally.

I've done some tests and am pretty sure it works, but it is possible I missed something. Hope this helps :)
pull/1122/head
ynamite 8 years ago committed by GitHub
parent
commit
8fb0b78bf3
  1. 36
      js/layout-modes/fit-rows.js

36
js/layout-modes/fit-rows.js

@ -7,7 +7,7 @@
/* jshint strict: false */ /*globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD
define( [
define( 'isotope/layout-modes/fit-rows',[
'../layout-mode'
],
factory );
@ -35,18 +35,40 @@ proto._resetLayout = function() {
this.y = 0;
this.maxY = 0;
this._getMeasurement( 'gutter', 'outerWidth' );
if(this.options.centered) {
this.rowCount = 0;
this.positioned = 0;
this.numItems = this.isotope.filteredItems.length;
}
};
proto._getItemLayoutPosition = function( item ) {
item.getSize();
var itemWidth = item.size.outerWidth + this.gutter;
// if this element cannot fit in the current row
var containerWidth = this.isotope.size.innerWidth + this.gutter;
if ( this.x !== 0 && itemWidth + this.x > containerWidth ) {
// items per row
if ( this.x !== 0 && itemWidth + this.x > containerWidth ) {
this.x = 0;
this.y = this.maxY;
}
}
if(this.options.centered) {
var itemsPerRow = Math.round(containerWidth / itemWidth);
var remainder = this.numItems % itemsPerRow;
var rows = Math.ceil(this.numItems / itemsPerRow);
var itemsLeftToPosition = this.numItems - this.positioned - 1;
if(this.x === 0) {
this.rowCount++;
if(remainder > 0 && rows === this.rowCount) {
var takenSpace = itemWidth * itemsLeftToPosition;
this.x = Math.round(( containerWidth / 2) - ( takenSpace / 2) - (itemWidth / 2));
}
}
}
var position = {
x: this.x,
@ -55,7 +77,11 @@ proto._getItemLayoutPosition = function( item ) {
this.maxY = Math.max( this.maxY, this.y + item.size.outerHeight );
this.x += itemWidth;
if(this.options.centered) {
this.positioned++;
}
return position;
};

Loading…
Cancel
Save