Vote count:
0
This problem is annoying me because it works with one set of images and not with another.
I have a this object:
function PreLoader(toLoad, parent, target) {
var errored = 0;
var loaded = 0;
var toLoad = toLoad;
function allLoaded() {
// reset the counters so it can be used again
loaded = 0;
errored = 0;
// determine which img is the tallest
var a = target[0].height();
var b = target[1].height();
var l = (a > b) ? a : b;
// set the height of the container to the tallest
// unless it's already bigger
if (parent.obj.height() < l)
parent.obj.css("height", l);
};
this.load = function() {
++loaded;
if (loaded + errored == toLoad)
allLoaded();
};
this.error = function() {
++errored;
if (loaded + errored == toLoad)
allLoaded();
};
}
I have been using it as follows:
var images = ["img.png", ...];
var parent = {obj: $("#some-img-container")};
var slabLoader = new PreLoader(images.length, parent, [external.slab, internal.slab]);
for (var i = 0; i < images.length; i++) {
var img = new Image();
img.src = images[i];
img.onload = slabLoader.load;
img.onerror = slabLoader.error;
parent.obj.append(img);
}
The problem is, sometimes it doesn't work. I have multiple sets of images that are absolute positioned because they are layered on top of each other, but they can be different heights. Obviously I can't hard code the heights because I don't know what they are before the page loads... and because absolute positioned elements don't affect their parents size I can't rely on things like height: 100%.
var l in the allLoaded() function sometimes returns 0 even though the images should be loaded by the time that is called.
Am I correct in this statement or am I doing something wrong and it only works sometimes because of luck?
The html looks like this:
<div class='wrapper-hover'>
<div class='wrapper-content'>
<a herf='#' id='some-img-container' class='viewport'>
<!-- this is where the image goes, added by the script -->
</a>
<div class='wrapper-caption'>
<label class='wrapper-caption-content'>Some Image</label>
</div>
</div>
</div>
Sorry if the question is a bit difficult to understand.
javascript loaded img still has 0 height
Aucun commentaire:
Enregistrer un commentaire