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?
2 Answers 2
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');
}
Comments
You need to pass the function to run in the callback as a reference. Try this:
$('#mydiv').load(toLoad, afterLoad); // Note the removal of ()