cnotethegr8
cnotethegr8

Reputation: 7510

jQuery add Height to parent

I have 8 tabs ranging in all different heights. Each having a similar class, and the active tab having its own class.

How can i get the height of the active tab and add it as a style to its parent? (When a different tab becomes active, the new height needs to be added.)

The code below is an example of what im trying to get. Thanks.

<div id="parent" style="height: 1426px;">
  <div class="child"></div>         ( height: 2245px )
  <div class="child"></div>         ( height: 983px )
  <div class="child"></div>         ( height: 3004px )
  <div class="child active"></div>  ( height: 1426px )
  <div class="child"></div>         ( height: 1209px )
</div>

Upvotes: 1

Views: 1391

Answers (3)

sandino
sandino

Reputation: 3842

This way:

 var child_selected_height = $('div.child.active').css('height');
$('#parent').css('height', child_selected_height);

or more simple:

$('#parent').css('height', $('div.child.active').css('height'));

Upvotes: 0

Martin Larente
Martin Larente

Reputation: 520

You can do it like this:

$('#parent').height($('.active').height());

However, since the child is under the parent, you should probably do this instead:

$('#parent').height($('.active').outerHeight());

If you want to set the height when a new tab is selected, you have to put that line at the same place where you set the "active" class. It could look something like this:

$('#parent').find('.child').click(function() {
    var $this = $(this);
    $this.addClass('active').siblings().removeClass('active');
    $('#parent').height($this.outerHeight());
});

Upvotes: 2

cpjolicoeur
cpjolicoeur

Reputation: 13106

var childHeight = $(".active", "#parent").height();
$("#parent").height(childHeight)

or in a one-liner

$("#parent").height( $(".active", "#parent").height() );

Upvotes: 2

Related Questions