jQuery Responsive Equal Height Method

Glenn Blog 0 Comments

There are so many methods too get a fluid equal height in jQuery, but in testing many (seriously loads) I’ve found that there’s usually a glitch and that’s often that the container doesn’t adjust on window resize. This is the best all round solution that I’ve come across to resolve this issue. In my example I’m applying it to the standard WordPress Gallery to ensure that it’s rows are of equal height on load and resize:-


<div id="gallery-1" class="gallery gallery-columns-3">
			
	<dl class="gallery-item">
	<dt class="gallery-icon portrait">
		<a href="image.jpg" data-options="thumbnail: 'iamge.jpg'"><img width="199" height="300" src="image-199x300.jpg" class="attachment-medium" alt=""></a>
	</dt></dl>
	
	<dl class="gallery-item">
	<dt class="gallery-icon portrait">
		<a href="image.jpg" data-options="thumbnail: 'iamge.jpg'"><img width="199" height="300" src="image-199x300.jpg" class="attachment-medium" alt=""></a>
	</dt></dl>
	
	<dl class="gallery-item">
	<dt class="gallery-icon portrait">
		<a href="image.jpg" data-options="thumbnail: 'iamge.jpg'"><img width="199" height="300" src="image-199x300.jpg" class="attachment-medium" alt=""></a>
	</dt></dl>
		
</div>

And here is the jQuery to give you Equal Heights on your Div / Li  etc



jQuery(function($){
equalheight = function(container){

var currentTallest = 0,
     currentRowStart = 0,
     rowDivs = new Array(),
     $el,
     topPosition = 0;
 $(container).each(function() {

   $el = $(this);
   $($el).height('auto')
   topPostion = $el.position().top;

   if (currentRowStart != topPostion) {
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
       rowDivs[currentDiv].height(currentTallest);
     }
     rowDivs.length = 0; // empty the array
     currentRowStart = topPostion;
     currentTallest = $el.height();
     rowDivs.push($el);
   } else {
     rowDivs.push($el);
     currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
  }
   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
     rowDivs[currentDiv].height(currentTallest);
   }
 });
}

$(window).load(function() {
  equalheight('.gallery .gallery-item');
});

$(window).resize(function(){
  equalheight('.gallery .gallery-item');
});
});

As with all our code this will work with WordPress.

About the Author
jquery responsive equal height method jQuery Responsive Equal Height Method 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

Your email address will not be published. Required fields are marked *