Last active
November 30, 2018 20:54
-
-
Save allanemerson/6ba6efbdeb7731ce321287a5a3d4e4cf to your computer and use it in GitHub Desktop.
Equalize heights
This file contains 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
/* | |
Usage: | |
equalizeHeights($('.your-target')); | |
Note: $w = $(window); and breakpoints = {}; defined elsewhere. | |
*/ | |
var equalizeHeights = function($elements){ | |
if( !$elements.length ) return; | |
var setHeights = function($elements){ | |
// reset for screen changes | |
$elements.height('auto'); | |
var maxHeight = 0; | |
var currentIndex = 0; | |
var currentOffset = $elements.first().offset().top; | |
var rows = [{ | |
height : maxHeight, | |
elements : [] | |
}]; | |
$elements.each(function(c){ | |
var thisHeight = $(this).outerHeight(); | |
var thisOffset = $(this).offset().top; | |
// if this item is on a new row, start the height calculation over | |
if( thisOffset != currentOffset ){ | |
maxHeight = 0; | |
currentOffset = thisOffset; | |
rows.push({ | |
height : maxHeight, | |
elements : [] | |
}); | |
currentIndex++; | |
} | |
// find the tallest | |
if( thisHeight > maxHeight ){ | |
maxHeight = thisHeight; | |
} | |
rows[currentIndex].height = maxHeight; | |
rows[currentIndex].elements.push( $(this) ); | |
}); | |
// set the height for each element in the row | |
rows.forEach(function(row){ | |
row.elements.forEach(function(item){ | |
item.height(row.height); | |
}); | |
}); | |
}; | |
$w.on('load', function(){ | |
setHeights($elements); | |
}); | |
$w.on('resize', function(){ | |
setHeights($elements); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment