Rik de Vos
Rik de Vos

Reputation: 3517

jQuery & CSS - match a div's height while animating

I have two <div>'s floated left within a parent <div>. Using jQuery, the div.will_slide_down will slide down at some point (using $("div.will_slide_down").slideDown()). When it is sliding down, the div.first's height should also increase to match the height of the div.second at the same time.

How can I do that?

 <div class="wrap">
      <div class="first" style="width: 200px; float: left;"></div>
      <div class="second" style="width: 700px; float: left;">
           <p>BlaBlaBla</p>
           <div class="will_slide_down" style="display: none">Some hidden text</div>
      </div>
 </div>

The only way I can think of is to run a function when the slideDown of the div.second is complete, but this will mess up the layout. It should happen at the same time.

Upvotes: 1

Views: 624

Answers (3)

Chris Pickett
Chris Pickett

Reputation: 2822

I think the best way would be to use .animate() and the step function. The step function is fired at each 'step' of the animation. Something like this should do the trick:

$('div.will_slide_down').animate({height: 'show'}, {step: function(now, fx){
    var new_height = $('div.second').height;
    $('div.first').css('height', new_height);
}});

Upvotes: 7

jeroen
jeroen

Reputation: 91734

What you could do, is position .will_slide_down somewhere off-screen - without hiding it - at page-load to measure its height. Then you can hide it, move it back and use the height (adding the initial height of .second...) to calculate the new height of .first and just animate the two at the same moment.

Upvotes: 0

Liam Bailey
Liam Bailey

Reputation: 5905

Assuming your slide down will be triggered by some event, try something like this:

$(document).ready(function() {
$("element").click(function() {
    follower($("div.first"));
$("div.will_slide_down").slideDown()).
})
    })

    function follower(el) {
        if ($("div.will_slide_down").is(":animated"))
        {
            var leader = $("div.will_slide_down");
            while(leader.is(":animated"))
                  {
                  el.animate({
                      height: leader.css('height')
                  },3000);
                  }
        }
    }

Upvotes: 2

Related Questions