DEV Community

Cover image for Equal Height in Vanilla JavaScript
Dhruvang Gajjar
Dhruvang Gajjar

Posted on • Edited on

Equal Height in Vanilla JavaScript

If you want to add equal height for the elements, you don't need any jQuery or JavaScript Plugins. Just add following script and use it for any elements.

You can also check the Demo

function setHeight(el, val) {
  if (typeof val === "function") val = val();
  if (typeof val === "string") el.style.height = val;
  else el.style.height = val + "px";
}

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

  Array.from(document.querySelectorAll(container)).forEach((el,i) => {
    el.style.height = "auto";
    topPostion = el.offsetTop;
    if(currentRowStart != topPostion){
      for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
        setHeight(rowDivs[currentDiv], currentTallest)
      }
      rowDivs.length = 0;
      currentRowStart = topPostion;
      currentTallest = parseFloat(getComputedStyle(el, null).height.replace("px", ""))
      rowDivs.push(el);
    } else {
      rowDivs.push(el);
      currentTallest = (currentTallest < parseFloat(getComputedStyle(el, null).height.replace("px", ""))) ? (parseFloat(getComputedStyle(el, null).height.replace("px", ""))) : (currentTallest);
    }
    for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
      setHeight(rowDivs[currentDiv], currentTallest)
    }
  })
}
Enter fullscreen mode Exit fullscreen mode

You don't need to change above code. Just put following code below main code and repeat it as many time as you want.

window.addEventListener("load", function(){
  equalheight('.blog-title')
})
window.addEventListener("resize", function(){
  setTimeout(function(){
    equalheight('.blog-title')
  })
})
Enter fullscreen mode Exit fullscreen mode

This code does not have any dependency. It is built in pure JavaScript.

Top comments (1)

Collapse
 
philsav2017 profile image
Philip

works well!!