jQuery ajax: Load and fadeIn

Hi,
This is an external html (external.html) I want to load into a page with ajax,

<div id="wrapper">
   <div id="contents">
     xxx
   </div>
</div>

This is the parent page,

<div>
    <ul>
        <li><a href="#" onclick="ajax_request(); return false;">1</a></li>
    </ul>
</div>

<div class="bottom" id="studies">
</div>

This is the ajax call which I am using Jquery,

function ajax_request() {
  $('#studies').html('<p>loading</p>');
  $('#studies').load("external.html");
  $("#contents").fadeIn(700);
}

I can load the external.html successfully, but I am not able to fade in the div with the id of ‘contents’ because it is inside the external.html

How do I get around to it?

Many thanks,
Lau

Ajax is asynchronous, which means once you make the call to fetch something, javascript doesn’t sit there an wait until its finished. It continues executing, and just does the download in the background, finishing it whenever it can.

This means the line of code following your call to load() executes immediately, which is probably well before anything is actually loaded. You need to wait until the data is loaded before trying to fade it in. Since you can’t really guess how long it will take for the loading to complete, load() accepts a callback function which jquery will execute once the operation is complete.

http://docs.jquery.com/Ajax/load


function iAmACallbackFunction() {
    $("#contents").fadeIn(700);
}

$('#studies').load("external.html", {}, iAmACallbackFunction);

Got it, many thanks for this. It works perfectly on my site.:smiley:
Cheers,
L