0

I have a folder which contains some images:

image1-1.jpg
image1-2.jpg
image2-1.jpg
image2-2.jpg
image2-3.jpg
image2-4.jpg
image3-1.jpg
image3-2.jpg

and a series of links:

link 1
link 2
link 3

I want to use just JavaScript so that when a user clicks on one of these links the corresponding images will be loaded and inserted into my webpage. I have tried with a for loop but it always inserts the amount of images of the highest 'category' of images. For example I click link 1 but it inserts 4 images because image2 goes up to 4.

I've tried this:

var category = <somenumber>
var img = new Image();
for(var i=1;i<375/*the max is 374 images*/;i++){
  img.src = "image"+category+"-"+I+".jpg";
  if(img.width != 0){
    $('<img src="'+img.src+'" width="200">').appendTo('#imgbox');// I use jquery to
  }
}

PS: I'm trying not to use php or anything like that

1 Answers1

1

According to the list of images, the names have the following scheme:

image<category>-<number>.jpg

Your for loop is generating images like

image<number>.jpg

How can this load any image? I assume, images like image<number>.jpg do actually exist, but as a side effect of the error, this is hiding the error.

Next: You create an image Object and within the loop you ar assigning a new src to this one image. Further, you are only using the URL of the image object, which already exists as string. Two possibilities:

1) create an image object within the loop:

for(var i=1;i<375/*the max is 374 images*/;i++){
  var img = new Image();

  $( img ).load(function() {
     if(this.width != 0){
        $(this).appendTo('#imgbox');
     }
  });
  img.src = "image"+i+".jpg";
}

Have a fiddle here

2) Just use the url, no image object:

for(var i=1;i<375/*the max is 374 images*/;i++){
  
    $('<img src=image'+i+'.jpg width="200">').appendTo('#imgbox');
}

And at least you need to correct what I wrote above regarding names of the images.

Community
  • 1
  • 1
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
  • The problem with this first option is that half of the images doesn't pop up because they are being checked before they have loaded. And the second one creates 374 img objects. – Tiel Van Hecke Feb 09 '14 at 18:42