Skip to content

Instantly share code, notes, and snippets.

@zackpyle
Last active October 17, 2023 18:45
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 zackpyle/89b6e4038a55c0f1ec2f43267f12ee78 to your computer and use it in GitHub Desktop.
Save zackpyle/89b6e4038a55c0f1ec2f43267f12ee78 to your computer and use it in GitHub Desktop.
Set separate equal heights for each row of content on the page. This eliminates large gaps in content further down caused by a single tall item but keeps the items in the row equal with each other.
// Add this to your indivdual pages
jQuery(document).ready(function ($) {
setEqualHeights('.myClass');
});
// And then add this to your global js
jQuery(document).ready(function ($) {
$.fn.equalHeights = function() {
var max_height = 0;
$(this).each(function() {
max_height = Math.max($(this).height(), max_height);
});
$(this).each(function() {
$(this).height(max_height);
});
};
window.setEqualHeights = function(selector) {
var items = $(selector);
if (items.length === 0) {
console.error('No elements matched by selector:', selector);
return;
}
if ($(window).width() > 768) {
var currentOffsetTop = items.first().offset().top;
var currentLine = [];
var lines = [];
// loop through each item and group them by line
items.each(function() {
if ($(this).offset().top !== currentOffsetTop) {
lines.push(currentLine);
currentLine = [];
currentOffsetTop = $(this).offset().top;
}
currentLine.push($(this));
});
// add the last line
lines.push(currentLine);
// set equal height for each line
lines.forEach(function(line) {
$(line).equalHeights();
});
$(window).resize(function () {
setTimeout(function(){
// reset height for all items
items.css('height','auto');
// group items by line again
currentOffsetTop = items.first().offset().top;
currentLine = [];
lines = [];
items.each(function() {
if ($(this).offset().top !== currentOffsetTop) {
lines.push(currentLine);
currentLine = [];
currentOffsetTop = $(this).offset().top;
}
currentLine.push($(this));
});
lines.push(currentLine);
// set equal height for each line
lines.forEach(function(line) {
$(line).equalHeights();
});
}, 500);
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment