Skip to content

Instantly share code, notes, and snippets.

@jsongerber
Created October 30, 2017 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsongerber/c891d46b84fc3e4e84f69a638ec69e8b to your computer and use it in GitHub Desktop.
Save jsongerber/c891d46b84fc3e4e84f69a638ec69e8b to your computer and use it in GitHub Desktop.
Buxum Columns Height
/*
Same height for every cols
Use:
$('.wrapper').BuxumColsHeight(boxSelector, numberCols, subElements);
boxSelector: jQuery selector of the boxes
numberCols: Number of columns
subElements: array of selectors inside .box, if supplied, those elements height will be changed, null to change .box height
*/
jQuery.fn.BuxumColsHeight = function(box, cols, elements){
this.each(function(){
// Vars
var boxes = $(box, this);
var numberBoxes = boxes.length;
var lastLineNumberBoxes = numberBoxes % cols;
var elementsHeight = [];
var subElements = false;
if (!elements){
elementsHeight[box] = 0;
}else{
subElements = true;
$.each(elements, function(key, value) {
elementsHeight[value] = 0;
});
}
// Loop through boxes
boxes.each(function(i){
var currentBox = $(this);
// Every last cols, set all cols of same line to the tallest element
Object.keys(elementsHeight).forEach(function(selector){
var currentSelector = subElements ? $(selector, currentBox) : currentBox;
if (currentSelector.height() > elementsHeight[selector])
elementsHeight[selector] = currentSelector.height();
});
// End of line, set every cols height and reset vars
if ((i + 1) % cols == 0){
var prevs = $(this).prevAll().addBack().slice(0, cols);
Object.keys(elementsHeight).forEach(function(selector){
var prevsSelector = subElements ? $(selector, prevs) : prevs;
prevsSelector.height(elementsHeight[selector]);
})
}
// If last elements
if (i == lastLineNumberBoxes - 1){
// If last line has less elements than cols
if (lastLineNumberBoxes != 0){
var prevs = $(this).prevAll().addBack().slice(0, lastLineNumberBoxes);
Object.keys(elementsHeight).forEach(function(selector){
var prevsSelector = subElements ? $(selector, prevs) : prevs;
prevsSelector.height(elementsHeight[selector]);
})
}
}
})
})
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment