Skip to content

Instantly share code, notes, and snippets.

@nick1n
Forked from namklabs/equal-height.js
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nick1n/9121900 to your computer and use it in GitHub Desktop.
Save nick1n/9121900 to your computer and use it in GitHub Desktop.
$.fn.equalheight = function( remove ) {
// Reset heights from the last viewport resize so that values do not get wacky-large.
this.height('auto');
// if remove is true, just reset the heights and return
if ( remove ) {
return;
}
// if there are less then two elements, we don't need to do anything return
if ( this.length < 2 ) {
return;
}
var groups = {},
group;
// for each element, add the element to groups with the same top position and find the tallest height
this.each(function () {
var $this = $(this),
top = $this.position().top,
height = $this.outerHeight();
// get the group with the same top position or create a new group object
group = groups[top] || { height: 0, $elements: $this };
// find the tallest height in the group
if ( group.height < height ) {
group.height = height;
}
// if the group already exists, add $this element
if ( groups[top] ) {
group.$elements = group.$elements.add( $this );
// else if its a new group, add the group
} else {
groups[top] = group;
}
});
// for each group, set their heights to the group height
for ( group in groups ) {
// this assumes all the elements have a box-sizing of border-box
groups[group].$elements.css( 'height', groups[group].height + 'px' );
}
};
$(window).load(function() {
$('.equal-height').equalheight();
});
$(window).resize(function(){
$('.equal-height').equalheight();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment