Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate the change of height of a div when its contents change

Tags:

jquery

I have a div#menu that displays a list of information. That information changes via ajax. When it changes, I want to animate that transition from height A to height B.

I know I can use .animate({'height': 'something') but I don't know how to glue all this together.

I am using jQuery.

How can I do that?

Edit.

The ajax call looks like this:

$.ajax({
  url: $(this).data('redraw-event-url'),
     dataType: 'script'
     }) 
like image 493
Nerian Avatar asked Feb 06 '12 17:02

Nerian


2 Answers

You can add the new HTML to the DOM off-screen so the user can't see it. Then get it's height, and change the height of the container just before moving the new HTML from the temporary off-screen location to it's final destination. Something like this:

$.ajax({
    success : function (serverResponse) {

        //add the new HTML to the DOM off-screen, then get the height of the new element
        var $newHTML  = $('<div style="position : absolute; left : -9999px;">' + serverResponse + '</div>').appendTo('body'),
            theHeight = $newHTML.height();

        //now animate the height change for the container element, and when that's done change the HTML to the new serverResponse HTML
        $('#menu').animate({ height : theHeight }, 500, function () {

            //notice the `style` attribute of the new HTML is being reset so it's not displayed off-screen anymore
            $(this).html($newHTML.attr('style', ''));
        });
    }
});
like image 170
Jasper Avatar answered Oct 15 '22 04:10

Jasper


I believe I have a cleaner, better solution involving a container:

<div id="menu_container">
  <div id="menu">
    <p>my content</p>
  </div>
</div>

What I do is that I lock maxHeight and minHeight of the container to the current height of the div. Then I change the content of said div. And finally I "release" max and min height of the container to the current height of inner div:

$("#menu_container").css("min-height", $("#menu").height());
$("#menu_container").css("max-height", $("#menu").height());
$("#menu").fadeOut(500, function() {

    //insert here the response from your ajax call
    var newHtml = serverResponse;

    $(this).html(newHtml).fadeIn(500, function() {
        $("#menu_container").animate({minHeight:($("#menu").height())},500);
        $("#menu_container").animate({maxHeight:($("#menu").height())},500);
    });
});
like image 1
Sheraff Avatar answered Oct 15 '22 05:10

Sheraff