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);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!