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.
you need to recalcutale "tallest" on every resize
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:
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.