How to load content dynamically with jQuery and then run code on it

If you’ve ever tried to run code on dynamically loaded content you’ll know it’s at best hit and miss, and most of the time it doesn’t even work. The problem is that the content you’re trying to alter is not loaded yet, so of course it doesn’t run.

Let’s say we need to load a div with some sort of content in it. Here’s the code, with comments so it’s all clear:

// get the data from testpage.php
jQuery.get('testpage.php', function(data){
	// insert the data
	jQuery('#targetdiv').html(data);
// done is a callback that waits for the GET request to be completed
}).done( function(){
	// move the inner div down 100 pixels
	jQuery('#targetdiv #innercontent').animate({top: '100px'});
});