05 July, 2010

Same height sub-divs using jQuery

Previous day i had to make height of all the child divs same. Actually i had 3 divs, with different height according to dynamic content, inside a main div, but i needed to make of all those child divs same irrespective of the content they had. So, i figured it out using s simple jquery code.
This code actually checks for a div that has maximum height, and then applies that max height to all the divs that is contained inside the main div. Check out the following code snippet.

//include your jquery.js file here
$(document).ready(function() {
//make a new array for storing the heights temporarily
var heightArr = new Array();
//loop through each of the child divs of parent div,
//i've used class of div, but it can be replaced with id as well
$(".mainDiv").children().each(function() {
var divHeight = $(this).height();
//push the height to array
//this is a function to get maximum value from an array
Array.max = function(array) {
return Math.max.apply(Math, array);
var maxHeight = Array.max(heightArr);
//now apply the maxHeight to all the divs css
$(".mainDiv").children().each(function() {
$(this).css('height', maxHeight);

No comments: