Recently I was working on one small project and I had to use minimum resources as it is accessible on mobile devices too. There was one requirement of equal height of two elements. So instead of depending of any third party code, I have created my own plugin with 649 bytes only!
Core function
$.nyeqh = function(selector1, selector2) {
var obj1 = $(selector1);
var obj2 = $(selector2);
obj1.each(function(){
var obj1_h = obj1.height();
var obj2_h = obj2.height();
if ( obj1_h > obj2_h ){ obj2.height( obj1_h ); }
if ( obj2_h > obj1_h ){ obj1.height( obj2_h ); }
});
return this;
}
Usage of this plugin
<script type="text/javascript">
$(function() {
$.nyeqh('.selector_1', '.selector_2');
});
</script>
<div id="eqh">
<div class="selector_1">
<p>Lorem ipsum ...</p>
</div>
<div class="selector_2">
<p>Lorem ipsum dollar sit amet...</p>
<p>Lorem ipsum dollar sit amet...</p>
</div>
</div>
Don’t forget to include jquery core js before $.nyeqh
function call !
February 25, 2013 at 3:39 pm
Hi, inspired by your code I just wroted my own implementation of this idea. My plugin code:
(function($) {
jQuery.fn.equalHeight = function() {
var h = [];
var hm = 0;
this.each(function(){
h.push( $(this).height() );
});
hm = Math.max.apply(Math, h);
return this.each(function(){
if ( hm && $(this).height() < hm ) {
$(this).height(hm);
}
});
};
})(jQuery);
Usage. All matched elements (not only two as in your example) will be „equalized“ to max height. E.g.:
…
…
…
jQuery(document).ready( function($) {
$(‘.eq’).equalHeight();
});
Note, that in both plugins (yours and mine) height value calculation is made specific to box model. It means, that if elements have different paddings and border widths – its up to browser to display heights equaly or not.
February 25, 2013 at 4:03 pm
Modified plugin to calculate correct height (box model):
(function($) {
jQuery.fn.equalHeight = function() {
var h = [];
var hm = 0;
this.each(function(){
h.push( $(this).outerHeight() );
});
hm = Math.max.apply(Math, h);
return this.each(function(){
if ( hm && $(this).outerHeight() < hm ) {
$(this).height( hm – ( $(this).outerHeight() – $(this).height() ) );
}
});
};
})(jQuery);