Jquery getting a hidden element's height
Asked Answered
R

3

11

I was trying to get a list of element's height value but it was returning 0.
I've done some research and saw that in order get element's height, that element must be visible.
But I want to check its height when it's hidden. If its height is bigger than some value use some functions then make it visible. Is there any way to do this?

I mean:

  1. Check hidden element's height.
  2. If it has OK value make it visible.
  3. If it doesn't have required value do some functions.
  4. Make it visible.
Revareval answered 2/2, 2012 at 18:21 Comment(3)
exact duplicate of #2346284Stormi
it works with hidden elements - jsfiddle.net/xgbEvImbibe
@ken redler: that is the best solution i found about this. i just had to use .appendTo('body') because it didn't work with .show()Grison
P
17

You can show the element get the height and then hide it, visually you will not see any difference.

var height = $('elementSelector').show().height();
$('elementSelector').hide();
if(height != <<HeightToCompare>>){
    //Code here
}
//Finally make it visible
$('elementSelector').show();

Demo

Paris answered 2/2, 2012 at 18:29 Comment(4)
I tought showing an element then hiding it will cause some visual issue but i test it now. Yes it's doesnt make any problem. Thanks for help.Revareval
But, if you look at my answer, you'll see you don't need to do that.Serve
@AlienWebguy - IE6 gives 0 if the element is hidden.Paris
This looks like it works..I too thought it would flicker but it doesn't.Zoology
B
6

One way is to clone the object, position the clone far outside the viewport, make it visible, measure the clone, then destroy it.

So you have:

<div id="maybe" style="display: none;">
  Something
</div>

Since you're using jQuery, you'd do something like this:

$('#maybe')
  .clone()
  .attr('id','maybe_clone') // prevent id collision
  .css({                    // position far outside viewport
    'position': 'absolute',
    'left': '-1000px'
  });

if( $('#maybe_clone').show().height() > 200 ) {
  $('#maybe').show();
}

$('#maybe_clone').remove();       // housekeeping
Beora answered 2/2, 2012 at 18:23 Comment(3)
+1, that or temporarily position absolutely and move the element itself. Since the element is hidden to begin with, it will not disturb the markup.Streak
If display:none is applied to a parent element, this won't work. A fix would be injecting the clone outside it's original parent: .clone().appendTo('body').Acquiescent
thanks to give me clue to calculate hidden div heightEncourage
R
0

Position the object so it is visible to the browser, but not the user: jQuery: Get height of hidden element in jQuery

Reference answered 2/2, 2012 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.