Wednesday, July 20, 2016

jQuery: Equal heights in div rows

Use the following javascript. Where $childEl is the class of the children divs.

//Usage: equalHeights('child element Class');
jQuery(document).ready(function($){
  window.equalHeights = function ($childEl) {

  // your function logic goes here
  var currentTallest = 0,
      currentRowStart = 0,
      rowDivs = new Array(),
      $el2015,
      topPosition = 0;

 $($childEl).css("height", "auto");

  $($childEl).each(function() {

    $el2015 = $(this);
    topPostion = $el2015.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 = $el2015.height();
      rowDivs.push($el2015);

    } else {

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

   }

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

  });

  };
});

No comments:

Post a Comment