Created
February 8, 2013 10:26
-
-
Save JensRantil/4737958 to your computer and use it in GitHub Desktop.
Reusable jQuery/JavaScript snippet to have groups of HTML elements with the same height.
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
<html> | |
<head> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function() { | |
equalizeHeights(); | |
} | |
</script> | |
<style> | |
.box { | |
/* setting narrow height to have different heights */ | |
width: 30px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="box" style="background-color: blue;float:right;" data-height-group="group1"> | |
This one box. It has the same height as the other box. | |
</div> | |
<div class="box" style="background-color: red;float:right;" data-height-group="group1"> | |
This another box. It has the same height as the first box. | |
</div> | |
</body> | |
</html> |
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
/** | |
* Make all elements in the same `data-height-group` group equal heights. | |
* | |
* Example: | |
* <div data-height-group="group1">Element one.</div> | |
* <div data-height-group="group1">Another element with the same height.</div> | |
*/ | |
function equalizeHeights() { | |
var maxheights = {}; | |
$('[data-height-group]').each(function() { | |
var group = $(this).attr('data-height-group'); | |
var height = parseInt($(this).height()); | |
if (maxheights[group] === undefined || maxheights[group] < height) { | |
maxheights[group] = height; | |
} | |
}); | |
for (group in maxheights) { | |
$('[data-height-group=' + group + ']').height(maxheights[group]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment