Reputation: 37377
I'm loading in some html via ajax, I need an event to catch on to when the new images are loaded...
becuase it's in a div and not a whole page, I can't use $(window).load(....
I've tried the following but it doesn't work:
$('.banners_col img:last').load(function(){.....
Upvotes: 7
Views: 3495
Reputation: 195992
You need to target the results of the ajax call before inserting them in the dom.
So you need to use the callback method provided by jQuery for this reason.
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
example at http://www.jsfiddle.net/gaby/Sj7y2/
If there are multiple images in the ajax response and you want to get notified when all of them are loaded then use this slightly modified version
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// count the number of images
var imgCount = $live.find('img').length;
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
imgCount--;
if (imgCount==0)
{
// the code in here is called when all images have loaded.
}
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
example at http://www.jsfiddle.net/gaby/Sj7y2/1/
If you remove the comments and the empty lines, it is not much code :) so do not get intimidated..
Upvotes: 7
Reputation: 8463
Try to use live function to trigger event for html elements from ajax
$('.banners_col img:last').live('change',function(){.....
Upvotes: -3