Last active
October 22, 2021 20:28
-
-
Save ethanmay/765eae0e426507182df3529670255a28 to your computer and use it in GitHub Desktop.
Vanilla JS way to equalize heights of elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://davidwalsh.name/javascript-debounce-function | |
function debounce(func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this, args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
const removeEqualHeightBelow = 768; | |
const groupQuerySelector = 'QUERY SELECTOR FOR GROUP'; | |
const elementQuerySelector = 'QUERY SELECTOR FOR ELEMENTS WITH EQUAL HEIGHTS'; | |
const equalizeElementHeights = debounce(function () { | |
const rows = document.querySelectorAll( groupQuerySelector ); | |
if( window.innerWidth <= removeEqualHeightBelow - 1 ) { | |
for (let i = 0; i < rows.length; i++) { | |
const columnsAuto = rows[i].querySelectorAll( elementQuerySelector ); | |
for (let j = 0; j < columns.length; j++) { | |
columnsAuto[j].style.height = "auto"; | |
} | |
} | |
} | |
else if( window.innerWidth > removeEqualHeightBelow ) { | |
for (var i = 0; i < rows.length; i++) { | |
const columns = rows[i].querySelectorAll( elementQuerySelector ); | |
var maxHeight = 0; | |
for (let j = 0; j < columns.length; j++) { | |
columns[j].style.height = "auto"; | |
var height = columns[j].clientHeight; | |
if( height > maxHeight ) { | |
maxHeight = height; | |
} | |
} | |
for (let j = 0; j < columns.length; j++) { | |
// set subtract padding and set height | |
columns[j].style.height = maxHeight - parseInt(window.getComputedStyle(columns[j], null).getPropertyValue('padding-top')) - parseInt(window.getComputedStyle(columns[j], null).getPropertyValue('padding-bottom')); | |
} | |
} | |
} | |
}, 250); | |
if (document.readyState === 'loading') { | |
document.addEventListener('DOMContentLoaded', equalizeElementHeights); | |
} else { | |
equalizeElementHeights(); | |
} | |
window.addEventListener('resize', equalizeElementHeights); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment