Get height of a hidden element using jQuery

It’s known that hidden elements doesn’t take space in the document unless they are not really hidden but invisible, using visibility:hidden.

Sometimes you need to know something about a hidden element before you actually show it, let’s say the height property of a DIV element. You can easily get that property value making the element displayable but invisible, that way the element would take space in the document and you can get the height or any other property value that isn’t available while the element is hidden.

The following code is a small jQuery plugin that takes a function as argument. The plugin clones a jQuery element, make it displayable but invisible, then inserts the clone right after the original element, executes the function on the context of the cloned element and returns the function result. The clone is removed from the DOM after the passed function returns.

[gist id=1085787]

To solve the problem of the height property I explained above you could use the following code:

var height = $('#i-am-hidden').sandbox(function(){ return this.height(); });

Comments

  1. September 1, 2010 at 8:58 pm

    Great great tip dude!
    I wanted to avoid thing like this, but the plugin ideia is so useful.

    Thanks for sharing 😀

    Cheers

    1. September 12, 2010 at 8:35 pm

      Thanks! I’m glad to help 🙂