views:

206

answers:

1

I am creating a simple image gallery, and I would like to create multiple sets of images. On the click of a link all of the images in the link's given set will change.

here is my current code:

<ul>
  <li><img src="image01.jpg" width="500" height="450"></li>
  <li><img src="image02.jpg" width="200" height="450"></li>
  <li><img src="image03.jpg" width="530" height="450"></li>
  <li><img src="image04.jpg" width="500" height="450"></li>
  <li><img src="image05.jpg" width="178" height="340"></li>
  <li><img src="image06.jpg" width="400" height="450"></li>
  <li><img src="image07.jpg" width="300" height="220"></li>
  <li><img src="image08.jpg" width="400" height="450"></li>
  <li><img src="image09.jpg" width="500" height="450"></li>
  <li><img src="image10.jpg" width="400" height="450"></li>
  <li><img src="image11.jpg" width="300" height="450"></li>
  <li><img src="image12.jpg" width="300" height="450"></li>
  <li><img src="image13.jpg" width="178" height="340"></li>
  <li><img src="image14.jpg" width="500" height="450"></li>
  <li><img src="image15.jpg" width="200" height="220"></li>
  <li><img src="image16.jpg" width="100" height="450"></li>
</ul>

For example, on the click of link1 the sources would all be changed to setA01.jpg, setA02.jpg, and on the click of link2 the souces would become setB01.jpg, and so on. Any help would be over-gratefully appreciated.

Thank-You

+2  A: 

If your numbers will always be "01, 02, 03, etc" you could use a function like the following:

function setBase(baseval) {
  var images = document.getElementById("mylist").getElementsByTagName("img");
  for (var i = 0; i < images.length; i++) {
    images[i].src = baseval + ((i<9)?0+i:i) + ".jpg"; 
  }
}

Using that against this list:

<a href="#" onclick="setBase('setA'); return false;">Set A</a>
<ul id="mylist">
  <li><img src="image01.jpg" /></li>
  <li><img src="image02.jpg" /></li>
</ul>

Would create the following (assuming 'setA' were passed in as an argument):

<ul id="mylist">
  <li><img src="setA01.jpg" /></li>
  <li><img src="setA02.jpg" /></li>
</ul>
Jonathan Sampson
+1 - was typing almost the exact same source code when yours popped up... d'oh! Just one thing though - wouldn't `i` be `0` on the first iteration? This would mean the first image would need to be setA00.jpg unless you used ++i in the loop or i+1 in the conditional.
Andy E
**Note:** This operates on a zero-based index. If you need the sources to begin with "1" you will need to increment the value within the `.src=` line.
Jonathan Sampson
You could move the `return false` to the function itself to reduce redundancy.
Tatu Ulmanen
@Tatu: Correct, but since the user didn't state nothing should follow, I felt it was safer placing it in the onclick rather than in the function itself.
Jonathan Sampson