Created
April 24, 2018 02:43
-
-
Save doubleedesign/54412bded2ddabdc4a188cdcefa18a3f to your computer and use it in GitHub Desktop.
Get the heights of all elements that match the given selector, and set all of them to the height of the highest one
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
/** | |
* Get the heights of all elements that match the given selector, and set all of them to the height of the highest one | |
* Note: According to https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead, a for loop is faster than forEach | |
* @param selector - the CSS selector to set to the highest | |
*/ | |
function setHeightToHighest(selector) { | |
// Get our items - returns a NodeList of elements | |
var items = document.querySelectorAll(selector); | |
// Create an array to store the heights | |
var heights = []; | |
// Get the height of each item and add it to the array | |
for (var i = 0, len = items.length; i < len; i++) { | |
var thisHeight = items[i].clientHeight; | |
heights.push(thisHeight); | |
} | |
// Get the highest | |
var highest = Math.max.apply(null, heights); | |
// Set the height of each item to the value of highest | |
for (var i = 0, len = items.length; i < len; i++) { | |
items[i].style.height = highest + 'px'; | |
} | |
} | |
/** | |
* Usage examples | |
* Note: I recommend running this when the page has loaded and on resize, not on document ready. The height may not be accurate on document ready because the content of the element, such as images and icons, may not have loaded yet. | |
*/ | |
window.addEventListener('load', function(){ | |
setHeightToHighest('.card-section ul.icons'); | |
}); | |
window.addEventListener('resize', function(){ | |
setHeightToHighest('.card-section ul.icons'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment