Equal Height in Vanilla JavaScript
Dhruvang Gajjar
Posted on March 8, 2021
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)
}
})
}
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')
})
})
This code does not have any dependency. It is built in pure JavaScript.
💖 💪 🙅 🚩
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
javascript Navigating the World of JavaScript: A Mechanical Engineer's Perspective on Learning and Challenges
November 25, 2024