tags:

views:

503

answers:

2

Hi all. I have a question that I'm not too sure about. Here is my scenario. I have a series of list items with links. Whenever a link is clicked, it inserts a "loading" image into a span and slides that down. After some operation is complete, the "loading" image is removed, and the content is put into place. The problem isn't with the slideDown itself, but after the operation is complete. Here is my code:

<ul>
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
    <li><a href="#">Item 4</a></li>
    <li><a href="#">Item 5</a></li>
</ul>

And the corresponding jQuery:

$("ul li a").click(function() {
    var t = $(this).parent();

    $(t).append("<span class='content'><img class='loading' style='display:block;' src='../../Content/loading.gif' /></span>");
    $(".content").hide().slideDown("slow");

    $.getJSON("/Home/DoStuff/?ran=" + ran, null, function() {
     var span = $(t).find(".content");
     $(span).html("blah");

     $(".loading").remove();
    });
});

And finally, the CSS for this:

.content { display:block;border:1px solid red; }
img.loading { padding: 1em; }

So, in this case, the loading image is inserted into the span with a 1em padding and appended to the list item. The span is then slid down to give it a nice effect. Whenever the operation is done, and the content is inserted, the span "jumps" up to height of the content. I was wondering how I could animate the changing in height from accommodating the height of the padded image to the height of the content. Thanks.

A: 

I would swap the span for a div and set a specific height to ensure a smooth animation. See Remy's article here.

Also in your code your using a variable called t. You dont need to keep wrapping it with $() since it is already a jquery object.

redsquare
Hey, thanks for the advice.
A: 

You need to do something like this:

$.getJSON("/Home/DoStuff/?ran=" + ran, null, function(data) {
    var div = t.children(".content");
    var h = div.height();

    div.html(data);
    var i = div.height();
    div.height(h);

    div.animate({
        height: i
    }, 500);

    t.children(".loading").remove();
});

Notice, after switching the "loading" element with whatever data you're returning, you want to get the height of the new stuff and then immediately set the height to what it was previously before the new stuff was switched. From there you can animate to the height of the new stuff.