jQuery make two divs have equal height

Your Two divs:

Not much stuff and very short.
A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines.

Your simple css:

#div1 {
   width: 200px;
   float: left;
   background-color: #0CF
   padding: 10px;
}
#div2 {
   width: 200px;
   float: left;
   background-color: #f47a21;
   padding: 10px;
}

Gives you this:
Screen Shot 2014-05-30 at 10.57.04 AM

But we want equal heights even if the content changes. So we add some jQuery:

var currentTallest = 0,
     currentRowStart = 0,
     rowDivs = new Array(),
     $el,
     topPosition = 0;

 $('.blocks').each(function() {

   $el = $(this);
   topPostion = $el.position().top;
   
   if (currentRowStart != topPostion) {

     // we just came to a new row.  Set all the heights on the completed row
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
       rowDivs[currentDiv].height(currentTallest);
     }

     // set the variables for the new row
     rowDivs.length = 0; // empty the array
     currentRowStart = topPostion;
     currentTallest = $el.height();
     rowDivs.push($el);

   } else {

     // another div on the current row.  Add it to the list and check if it's taller
     rowDivs.push($el);
     currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

  }
   
  // do the last row
   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
     rowDivs[currentDiv].height(currentTallest);
   }
   
 });

Now we have to add the blocks class to the divs that we declared in the jQuery:

Not much stuff and very short.
A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines. A ton of stuff on multiple lines.

Yay! Equal div heights.
Screen Shot 2014-05-30 at 10.57.50 AM

Leave a Reply

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

+ 33 = 38