views:

59

answers:

2

I'm having a nightmare with a simple function!

I want it to:

  1. read the height of a div with existing content in it
  2. Update the div with the new content (supplied to the function)
  3. Read the height the div should be, but set it to the original height.
  4. Animate the div's height to adjust and fit the new content.

Code is as follows:

// function to display status content by animating the height of the status message
function slideStatus(content){

    // get current height
    var status_origheight = $("#status-message").height();

    // insert new content
    $("#status-message").html(content);

    // get new height
    var status_newheight = $("#status-message").height();

    // set the height to the orig value, hiding overflow content
    $("#status-message").height(status_origheight).css("overflow","hidden");

    // animate the div to the new height
    $("#status-message").animate({height:"+="+(status_newheight - status_origheight)+""}, 1000);

}

When i run this, it appears to ignore the fact that the content has changed, and just use the original height (therefore do no animation as it thinks the height has not changed).

Please help if you can!! It's driving me nuts.

+4  A: 

Work for me. Your bug is likely elsewhere... http://jsfiddle.net/6aBfD/

UPDATE

http://jsfiddle.net/6aBfD/3/

But that only works once. The problem is that you are relying on an element to set it's own height and read from that. But after the first run, you lock the height to a specific value. The updated link has the correct working clode, click it multiple times. I added the following:

$("#status-message")
    .css("overflow","visible")
    .css("height", "auto");

Now when you read the height it will be it's natural height. Then set the oveflow and height again later to lock it back down to what you want.

Squeegy
Squeegy you legend!That did the trick - the overflow rule was still set from a previous run on the div.Many thanks indeed!!!
Rob
A: 

Rob,

Try the following instead of .height():

var status_origheight = $("#status-message").css('height');

Adam
How are you calling the slideStatus function. That could likely be the problem.
Adam