views:

949

answers:

3

When writing a Javascript a function that I had gotten help from earlier, which gets the height of an element that is hidden, someone reffered me to the Prototype function getDimensions(). In the example, they set "visibility: hidden; position: absolute; display: block;", which effectively lets us measure what the clientHeight would be if it were being displayed. Then they set it all back and you can go about your business. I haven't used prototype, but I would assume that works fine. However, when I tried to mimic the same function in my own code, the use of "position: absolute;" threw off the measurement. It works fine without it, but its use is what allows us to do this for a split second without skewing the design. My version is below, any idea why it isn't working?

 var objStyle = obj[objName].style;

 // Record original style values
 var visibility = objStyle.visibility;
 //var position = objStyle.position;
 var display = objStyle.display;

 // Modify object for measuring
 objStyle.visibility = "hidden";
 //objStyle.position = "absolute";
 objStyle.display = "block";

 // Measure height
 height = obj[objName].clientHeight;

 // Fix object
 objStyle.visibility = visibility;
 //objStyle.position = position;
 objStyle.display = display;

 // Return height
 return parseInt(height);

Thanks in advance for your help.

A: 

I don't know if it works while invisible, but jQuery has some options here - in particular the height function; worth a look? Based on your example, something like:

height = $(obj[objName]).height();
Marc Gravell
A: 

Are you seeing this only on a cetain browser, or on all browsers? Prototype's getDimensions() does a check for Safari (and possibly other buggy browsers), you should try putting that in your code as well and see if it fixes the issue.

It could also be due to the fact that you're using obj[objName] as opposed to document.getElementById() - AFAIK these will return slightly different objects, which could cause the inconsistency you're seeing.

Ian Kemp
I should have posted more of my code. obj[objName] is a reference to an array that holds the object as retrieved via getElementById().I've tested my code in Safari 3, last night's WebKit build and Firefox 3.0.7The check that Prototype does is irrelevant in my case since display is equal to none
Bloudermilk
A: 

I usually measure my heights with .offsetHeight, something like:

var h = document.getElementById(divname).offsetHeight;

When I need to measure something, if it has position:absolute;

I usually run into this when I have two columns and one is absolute, and the parent needs to be pushed down by the one that's absolute if that's bigger than the other one. I'll use the offsetHeight to set the parent height if it's bigger that the height of the other column.

George Sisco