views:

33

answers:

2

This may be a bit silly question, but I just started doing pretty things in jQuery and I suddenly wondered how to solve a problem that I never even bothered looking into without the help of frameworks.

Suppose we have two div elements:

<body>
    <div id="lorem1" style="display:block; height:400px;">
        Lorem ipsum...
    </div>
    <div id="lorem2" style="display:hidden;">
        dolor sit amet...
    </div>
</body>

Now if we wanted to use an accordion effect to shrink the first div out of existence and grow the second one into existence, I'd assume we'd have the following simple logic:

  1. Iteratively decrease the height of #lorem1 until it reaches 0
  2. Set #lorem1 to display:none;
  3. Set #lorem2 to display:block; height:0;
  4. Iteratively increase the height of #lorem2

Then the problem... Increase the height of lorem2... until when? How do we know the final height of our element? We clearly can't pick a static value like "increase it until it reaches 400px", because the content of lorem2 might be more than 400 pixels tall. Alternatively if it's less than 400 pixels then any background colors/images or other elements on the page may not look right.

So how do we figure out when to stop our accordion?

A: 

using jQuery you could use the handy toggle attribute:

$('#lorem').animate({
  height: 'toggle'
});

I'm sure other js-libraries offer similar possibilities.


EDIT: Another approach would be animating the object until a height of auto. Or don't hide it via CSS, get the dimensions of the object via JS and hide it afterwards using JS. Now you know the dimensions to show it again.

pex
Seeing as there's no way to know the height of "auto", I suppose storing the dimensions at page load might be the only option. Unless it's possible to set the height to auto while it's still hidden, get the height, then set the height to 0 and unhide...
steven_desu
A: 

I think .slideDown() and .slideUp() will do that for you: http://api.jquery.com/slideDown/

banjomonster
Wasn't away jQuery had that feature, but unfortunately that doesn't answer my original question =) How does jQuery know when to stop sliding?
steven_desu