Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Multiple Image Sources Javascript

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.

like image 927
MRAISKY Avatar asked Nov 05 '22 17:11

MRAISKY


1 Answers

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>
like image 111
Sampson Avatar answered Nov 11 '22 04:11

Sampson