Created
June 10, 2015 08:03
-
-
Save aarongeorge/e951e08fe9bb42ab0006 to your computer and use it in GitHub Desktop.
Equal Height Children
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
/** | |
* Equal Height without using Table or flexbox | |
*/ | |
var EqualHeightChildren = function (container, childrenSelector) { | |
'use strict'; | |
this.container = container; | |
this.options = { | |
childrenSelector: '*' | |
}; | |
// Make childrenSelector a wildcard if it isn't passed | |
if (childrenSelector === undefined) { | |
this.options.childrenSelector = '*'; | |
} | |
// Child elements | |
this.children = this.container.querySelectorAll(':scope > ' + this.options.childrenSelector); | |
// Start the init | |
this.init(); | |
}; | |
EqualHeightChildren.prototype.init = function () { | |
'use strict'; | |
this.setHeights(); | |
this.bindResizeListener(); | |
}; | |
EqualHeightChildren.prototype.removeHeights = function () { | |
'use strict'; | |
// Remove any heights that I have applied | |
for (var i = 0; i < this.children.length; i++) { | |
this.children[i].style.removeProperty('height'); | |
} | |
}; | |
EqualHeightChildren.prototype.getHeights = function () { | |
'use strict'; | |
// Heights of children elements | |
var heights = []; | |
// Loop over all children elements | |
for (var i = 0; i < this.children.length; i++) { | |
// Push height to heights array | |
heights.push(this.children[i].offsetHeight); | |
} | |
// Return the heights | |
return heights; | |
}; | |
EqualHeightChildren.prototype.getMaxOfArray = function (array) { | |
'use strict'; | |
// Return the max | |
return Math.max.apply(null, array); | |
}; | |
EqualHeightChildren.prototype.setHeights = function () { | |
'use strict'; | |
var maxHeight = this.getMaxOfArray(this.getHeights()); | |
for (var i = 0; i < this.children.length; i++) { | |
if (this.children[i].offsetHeight < maxHeight) { | |
this.children[i].style.height = maxHeight + 'px'; | |
} | |
} | |
}; | |
EqualHeightChildren.prototype.bindResizeListener = function () { | |
'use strict'; | |
// Save a reference to this for the event listener | |
var self = this; | |
// Save a reference to the resize debounce | |
var debounce; | |
// Add the event listener to window resize | |
window.addEventListener('resize', function () { | |
// Clear the timeout | |
clearTimeout(debounce); | |
// Start a new timeout | |
debounce = setTimeout(function () { | |
self.removeHeights(); | |
self.setHeights(); | |
}, 100); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment