Reputation: 1057
I am trying to count all img in a div. To add images to the div I use a jquery function that looks like this :
function AddImages(namearray, amount, speed) {
...
}, speed)
All images are correctly added to the div element. .
After this I want to count the amount of image tags by using this :
var count = $("#myDiv").find('img').length;
OR
var count = document.getElementById("#myDiv").getElementsByTagName("img").length
Although the function AddImages() was executed before the count, this didn't worked.
Does anyone has an idea about this?
Upvotes: 0
Views: 127
Reputation: 93561
The problem is that the images are added over the course of a number of frames, but the function returned immediately, so no images have been added yet to count.
You can either add a callback to AddImages
(preferred), so that you know when the images are all added, or simply wait for a period of time before checking (which is effectively what you did with the debugger).
e.g.
var i = 0;
var uniekeid = 0;
function plaatsRandomPion(naamarray, aantal, snelheid, callback) {
setTimeout(function () {
uniekeid = uniekeid + 1;
var xpictures = Math.floor(sizepictures * Math.random())
var item = $("<img src='" + naamarray[xpictures] + "' id='" + uniekeid + "' />").hide().fadeIn();
$('#depionnen').append(item);
console.log(item);
i++;
if (i < aantal) {
plaatsRandomPion(naamarray, aantal, snelheid, callback);
}
else {
// We are done... callback to let the caller know
// Note: check whether the callback exists first
callback && callback();
}
}, snelheid)
}
And call like this:
plaatsRandomPion(pictures, 20, 100, function(){
var count = $("#box").find('img').length;
// Now the count will be set!
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/kcffgq26/4/
A more "modern" solution would be to use jQuery promises, but that is too much for this simple problem for now.
Note: having global settings outside a function (e.g. uniekeid
& i
) is usually a sign of non-reusable code. You can get the same effect, with no counters, by simply reducing the array each time with slice
and passing the shorter array recursively until it is empty. As you appear to want a random selection of images, I would suggest randomly sorting the array first (to avoid duplicate images).
Upvotes: 2