Equal Height in Vanilla JavaScript

dhruvangg

Dhruvang Gajjar

Posted on March 8, 2021

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.

💖 💪 🙅 🚩
dhruvangg
Dhruvang Gajjar

Posted on March 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related