Reputation: 2915
I add images dynamically, simply but appending an img tag, with a dynamic source, to an existing div. But, not all of these images will exist, and I would like to hide the ones, that doesn't.
I believe I can use load() and setup a hide function on error, but since I add them, simply by creating an img tag, I don't really know how to hook up my jquery to it.
Here is my add function:
function GetImages() {
$('#ImageContainer').empty();
$('#ImageContainer').css("visibility", "visible");
var regex = new RegExp("(.+?);", "g");
var match;
while (match = regex.exec($("#<%= HttpSources.ClientID %>").val())) {
$('#ImageContainer').append('<div class="ImgBox"><img src="' +
match[1].format($("#<%= ItemNo.ClientID %>").val()) + '" class="Image" /></div>');
}
return false;
}
It adds a div with an img, into another div.
Originally, I wanted to do something like this, to hide them, but since the divs and images doesn't exist when the document is loaded, I don't really see how I can hook it up to them.
$(document).ready(function() {
$(".ImgBox").Next(".Image").load(function () {
// ... loaded
}).error(function () {
// ... not loaded
$(this).hide();
});
});
Upvotes: 0
Views: 189
Reputation: 2915
I hate to answer my own question, but here's what I ended up with.
.live() sounded great, but unforunately, it doesn't work with load/error on the img.
Instead, I found this: http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not which seems to give me a way to check, if an image is loaded. After adding all the images, I will run them through, and clean up the not loaded.
Upvotes: 0
Reputation: 4736
EDIT: It turns out that browsers do not bubble the error event as they should. Because event bubbling is the mechansim behind the jQuery .live() functionality, then your bound event will not fire.
As an alternative I would suggest attaching the event to each element (or set of elements) as you add them.
Use live() to add events to elements that don't exist when you load the page.
e.g.
$(".ImgBox").Next(".Image")
.live("load", function () {
// ... loaded
}).live("error", function () {
// ... not loaded
$(this).hide();
});
Upvotes: 1