views:

356

answers:

4

HI all,

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.

Is the solution to show it, grab the width, then hide again? There must be a better way...

Cheers all

Gausie

+7  A: 

The only thing I can think of is to show it (or a clone of it) allow retrieval of the offsetWidth.

For this measurement step, just make its position absolute and its x or y value a big negative, so it will render by not be visible to the user.

Peter Bailey
Nice one, Peter. Thanks.
Gausie
Here is a blog post on this topic. One problem this method could encounter is resetting the position back to the original value. Using the swap method works good in this situation. http://bit.ly/6KwGzm
T B
+6  A: 

The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.

Otherwise, yes, show-measure-hide does work.

bobince
A: 

thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.

Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.

prodigitalson
A: 

Two options:

  1. position the element outside the viewport (ex: left:-10000px)
  2. use visibility: hidden or opacity: 0 instead of hide().

Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...

David