Fer P
Fer P

Reputation: 15

how to change several images with a single click

Im really new to javascript, and while Im learning, Im trying to change images in a gallery to others with an onclick function. I have links to different galleries. When I click on link 1, the imgs are one1.jpg, one2.jpg and so on. When I click on link 2, imgs are two1.jpg, two2.jpg, etc.

This is the rough script I made for Link 1:

<script>
  function one() {
    document.getElementById("foto1").src="one1.jpg";
    document.getElementById("foto2").src="one2.jpg";
          }
</script>


<a href="#" onclick="one()">Link 1</a>
<a href="#" onclick="two()">Link 2</a>     
<img id="foto1" src="tre1.jpg"></a>
<img id="foto2" src="tre2.jpg"></a>

etc.

I made another function called two() for the second link with same content but changing src to what I want. And for every link I add, I copy the script and change it a little. I know there is a way to optimize to a single script with variables or something . Any help? Thanks

Upvotes: 1

Views: 154

Answers (1)

Anupam Singh
Anupam Singh

Reputation: 1166

In order to differentiate group of images there must be a pattern. try to add a class on each img tag to differentiate images for changing their source, and the you can loop through images as follows:

    <a href="#" onclick="one()">Link 1</a>
    <a href="#" onclick="two()">Link 2</a>     
    <img class="img1" id="foto1" src="foto1.jpg">
    <img class="img1" id="foto2" src="foto1.jpg">

    <img class="img2" id="foto3" src="pic1.jpg">
    <img class="img2" id="foto4" src="pic2.jpg">
    <script>
  function one() {
      var img = document.getElementsByClassName("img1");
      for (var i in img) {
          img[i].src = "foto" + 1 + ".jpg"
      }
  }

  function two() {
      var img = document.getElementsByClassName("img2");
      for (var i in img) {
          img[i].src = "pic" + 1 + ".jpg"
      }
  }
  </script>  

Upvotes: 1

Related Questions