February 25, 2013
jQuery: Count images
Question by Jones-Rocks
I have a folder with images named example_**_title.jpg
.
I want to count these images with jQuery/Javascript and return the number of images.
I tried:
count = 0;
for (var i=0; i<=10; i++){
var bg_url = 'http://www.example-url.com/example_'+i+'_title.jpg';
$.get(bg_url)
.done(function(){
count++;
})
.fail(function(){
});
}
alert(count);
Thanks for the help.
Jones
Answer by Michael Laffargue
Since you don’t want to get
the files but just count, you can use type:'HEAD'
It should reduce the amount of data :
$.ajax({
url:'http://www.example-url.com/example_'+i+'_title.jpg',
type:'HEAD',
error: function()
{
//file doesn't exist
},
success: function()
{
count++;
}
});
Answer by Starx
Your code should work, this is a quote missing on your code. I hope that is just a typo.
count = 0;
for (var i=0; i<=10; i++){
var bg_url = 'http://www.example-url.com/example_'+i+'_title.jpg';
$.get(bg_url, function(data){ count++; });
}
alert(count);