3

On my page, I have following document ready function:

$(document).ready(function(){
 $('a').click(function(){
 var toLoad = $(this).attr('href')+' #newdiv'; 
 $('#mydiv').html('<p><img src="images/ajax-loader.gif" /></p>');
 $('#mydiv').load(toLoad, afterLoad()); 
 function afterLoad() {
 alert('test');
 } 
 return false; 
 });
});

When a link is clicked, the content of #newdiv from the target link is loaded into #mydiv on the current page. Before loading, I replace the current content of #mydiv with an animated gif. When loading is finished, the animated gif disappears and in there goes the new content. All this is working perfectly.

However, after loading is finished, I want to execute a new function called afterLoad. For the moment, I've only added an alert. The strange thing is that the alert box appears when still showing the animated gif, so when the new content still is loading. Is there another way to execute afterLoad when the new content is already in place?

Rory McCrossan
338k41 gold badges322 silver badges353 bronze badges
asked Dec 20, 2012 at 12:00

2 Answers 2

3

change to:

$('a').click(function(){
 var toLoad = $(this).attr('href')+' #newdiv'; 
 $('#mydiv').html('<p><img src="images/ajax-loader.gif" /></p>');
 $('#mydiv').load(toLoad, afterLoad);
 });
function afterLoad() {
 alert('test');
} 
answered Dec 20, 2012 at 12:04
Sign up to request clarification or add additional context in comments.

Comments

3

You need to pass the function to run in the callback as a reference. Try this:

$('#mydiv').load(toLoad, afterLoad); // Note the removal of ()
answered Dec 20, 2012 at 12:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.