Call a function on every resize and load

22 Views Asked by At

I am trying to make all divs with the same class the same height when loaded and whenever the window is resized. How can I call this function on load and whenever the screen resized? I'm trying to avoid using jQuery.

(function matchHeight() {
  var getCardBodyHeight = document.getElementsByClassName("card-body-height");

  var arrayLength = getCardBodyHeight.length;
  var heights = [];

  for (var i = 0; i < arrayLength; i++) {
    heights.push(getCardBodyHeight[i].offsetHeight);
  }

  function getHighest() {
    return Math.max(...heights);
  }

  var tallest = getHighest();

  for (var i = 0; i < getCardBodyHeight.length; i++) {
    getCardBodyHeight[i].style.height = tallest + "px";
  }
})();

I've tried using

  window.addEventListener("resize", function () {
    for (var i = 0; i < getCardBodyHeight.length; i++) {
      getCardBodyHeight[i].style.height = tallest + "px";
    }
  });

However, this only adjusted the heights when the screen was resized once instead of everytime. It also did not work when the page loaded.

1

There are 1 best solutions below

0
emilianoc On

you need to recalcutale "tallest" on every resize

window.addEventListener("resize", function () {
 //something like this is needed:
 var tallest = getHighest();
 for (var i = 0; i < getCardBodyHeight.length; i++) {
  getCardBodyHeight[i].style.height = tallest + "px";
 }
});

but if I can give you some advice:

be carefull with resize event because it fires a lot of time if the window is dragged its better do your stuff when resize is ended or paused like:

window._resizeIID=0;
window.addEventListener("resize", function () {
  //combining clearInterval and setTimeout will give some breath to your processor
  clearInterval(window._resizeIID);
  window._resizeIID=setTimeout(()=>{
    var tallest = getHighest();
    for (var i = 0; i < getCardBodyHeight.length; i++) {
      getCardBodyHeight[i].style.height = tallest + "px";
    }
  },200);
});

and for last but the most important if you can achieve the same result using css just use css

i hope this can help you in some way, have a nice day.