Brady
A moan, a groan, my life story and how me, a technically minded person just can't seem to fit in with anybody.

Archive for August, 2008

Javascript Same Height Div’s Update

A while back I posted a way of making same height div’s but came across an issue when padding was involved. Well I’ve modified my code to take into account padding. Now the obvious thing to do would be to be to check padding on a div and subtract it from the height, but it’s not that easy. You would have to check three things: padding, paddingTop and paddingBottom. For some reason when I was checking padding I couldn’t get a value from JavaScript, this had me really stumped but after a nights sleep I came up with a better and more simpler way of sorting the padding issue. This is to let the code run and let it re-height the div’s and let the padding mess things up then run the same thing again and check for height differences from last time we checked. Oooohhh look the height has gone up 10px from last time thanks to a padding of 5px on the div. Now we know there is 10px of padding lets remove it. Sorted!

JavaScript Code:
[js]
function sameHeight(divs) // Bring in an array of your divs
{
var highest = 0;
var heighttu = 0;
for(i = 0; i < divs.length; i++) // Loop through the divs { // Check to see if this div is the highest? if(document.getElementById(divs[i]).offsetHeight > highest)
{
// Yes its the highest so set the highest value to this div’s height
highest = document.getElementById(divs[i]).offsetHeight;
}
}
// Loop through divs and set their hieght all the same
for(i = 0; i < divs.length; i++) { document.getElementById(divs[i]).style.height = highest+"px"; } // now get offset hieght again and we may found we have gone higher this is because of padding if(document.getElementById(divs[0]).offsetHeight > highest)
{
// correct the height
highest = highest – (document.getElementById(divs[0]).offsetHeight – highest);
// Correct divs
for(i = 0; i < divs.length; i++) { document.getElementById(divs[i]).style.height = highest+”px”; } } }[/js]