views:

199

answers:

2

I need to calculate a top position for an element of variable height, so I was thinking of doing the following:

  1. Move the element 1000px off the top of the viewport
  2. Set the element to display: block
  3. Get the height of the element
  4. Set the element to display: none
  5. Continue on as if everything is normal and good

Does anyone see any pitfalls in this approach? Is there a more elegant solution I'm missing? Thanks!

+3  A: 

I'd look at prototype's implementation of getDimensions.

It sets the position to absolute, visibility to hidden, and display to block briefly. I've written one which handles getting the height of something which is contained within a display:none element, but it's a bit shonky in some edge cases.

wombleton
That would get around having to move the element off the screen. It does mean I can set both properties in the same CSS call, rather than in sequence.
Andrew Hedges
visibility=hide, and display:block is the way to go. I did something similar in here: http://stackoverflow.com/questions/282758/truncate-a-string-nicely-to-fit-within-a-given-pixel-width#283994
some
A: 

can you not just set the visibility to hidden and get the offsetHeight?

Steven A. Lowe
That looks like a viable technique, yes.
Andrew Hedges