Malixxl
Malixxl

Reputation: 525

Jquery getting a hidden element's height

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.

Upvotes: 11

Views: 24617

Answers (3)

Ken Redler
Ken Redler

Reputation: 23943

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

Upvotes: 6

Nathan Hase
Nathan Hase

Reputation: 659

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

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

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

Upvotes: 17

Related Questions