Jquery: Get height of hidden element in jQuery
Obtain the height of a hidden element swiftly by:
- Cloning it using
.clone()
. - Styling it for visibility (
display: 'block'
) and placing it off-screen (position: 'absolute', left: '-9999px'
). - Appending it to the body and measuring with
.outerHeight()
. - Deleting the clone right away.
Snippet:
This method allows you to extract the height without disturbing the layout or visibility.
No show, but tell: The stealth approach
For your eyes only: Absolute Positioning and Visibility
Here, the hidden element's CSS is temporarily set to position: 'absolute'
and visibility: 'hidden'
to measure the height and then restore the original state. As we like to say, now you see me, now you don't!
Snippet:
I've got the power: jQuery Plugins
The jQuery Actual plugin acts as a secret agent, morphing the element to get the accurate height and restoring it back, all while maintaining layout integrity.
Snippet:
When the going gets tough: Handling edge cases
Look, mom! I cloned it: Handling CSS inheritance
When cloning an element, remember to set the same dimensions as its parent for accuracy (Remember, cloned elements aren’t like magical twins that share the same wardrobe, okay?)
Hide and Seek: Visibility vs Display
Understand that visibility: hidden
doesn't remove the element from the layout, but display: none
does (They are like ghosts that do and don’t rattle the chains, respectively).
Doctor Who? Restoring the original state
Make sure to restore the original CSS of elements post measurement. We don’t want any unexpected time and space rifts, yeah?
Pro tips: Additional insights
Speed is key: Optimising performance
Avoid frequent DOM modifications for better performance. Try to minimise the operations and revert swiftly like a ninja (no traces left behind)
Beware, cascade ahead: Handling CSS inheritance
Your style changes might cascade down to child elements. Keep the measurement process in a protective bubble to avoid ripple effects in the layout (No butterfly effect here!)
Smooth sailing: Avoid reflow
Take measurements at times that cause minimal content reflow. This ensures a smooth user experience (Like perfect waves for surfing, dude!)
Was this article helpful?