Search code examples
javascripthtmldomdynamicanimated

Div Animate Auto Height


I am working in JavaScript and am unable to use any libraries such as J Query or CSS animations.

I have a Div with an undefined height that auto resizes based on the content that it contains.

The content is changed dynamically through setting the innerHTML value. This works well but the Div size change is jumpy and unappealing. I would like to animate the change in height.

I have seen much code covering this topic but all of the solutions were based on libraries or CSS animations.

Here are my thoughts on how to accomplish the animated dynamic change in height

//get the current height of the div holder
var heightStart = document.getElementById("divHolder").clientHeight;

//the new height, currently I don't know to obtain this
var heightEnd = 1000; 

//start a timer to animate the height change 
var timer = setInterval( function() {

    //clear timer if old height reached new height
    if ( heightStart >= heightEnd ){
        clearInterval(timer);
    }

    //set new height
    element.style.height= heightStart ;

    //incrementing height gradually
    heightStart = heightStart  + ( heightStart * 0.1 );

} , 50);

So the problem I am having is how to know what the new height would be as it will always be different depending on screen size and the content.

I was thinking I could set the height of the div to a fixed height equal to the heightStart. Then set overflow to none. Then set the new innerHTML content. So the Div wont auto change to fit the new content. I would then use the animate function above to gradually increase the height until the content is fully viewable.

The problem would be is that I don't know how to figure out when the auto height, or when all the content has been displayed height, has been reached.

Thoughts?

Thanks.


Solution

  • First, your heightStart should be assigned before apply new content. and after the new content come in. You can get it's size to heightEnd.

    var heightStart = document.getElementById("divHolder").clientHeight;
    
    // APPLY NEW CONTENT HERE
    document.getElementById("divHolder").innerHTML = NEW_CONTENT
    
    document.getElementById("divHolder").style.height = 'auto';
    var heightEnd = document.getElementById("divHolder").clientHeight;
    
    document.getElementById("divHolder").style.height = heightStart;
    document.getElementById("divHolder").style.overflow = 'hidden';