Search code examples
javascriptimagereplacesrc

Replace SRCs of Two Images with One Click


I am trying to do something that is slightly more complicated than I am used to, and I was hoping you guys could help me with this one... The website I am developing requires this type of Psudo

<script>
function FirstPic(){
        document.titlepic.src = document.rep1.src
        return
    }

function SecPic(){
        document.submitpic.src = document.rep2.src
        return
    }
</script>

// Calling Image Replacements
<img style="visibility:hidden;width:0px;height:0px;" name="rep1" src="title2.gif>
<img style="visibility:hidden;width:0px;height:0px;" name="rep2" src="submit2.gif>
// End of Calling Image Replacements

// Output Area
<img src="title.gif" name="titlepic">

<input type="radio" onclick="FirstPic();SecPic();updateProductPrice(this);parent.specs.location='<?php echo $options_item['base_var'] ?>.htm';">

<img src="submit.gif" name="submitpic">
// End of Output Area

Solution

  • You can replace the sources of as many images as you would like with a single click. And a single function, you don't need a function per each image.

    demo

    HTML:

    <img src='source-img-1.jpg' class='s'>
    <!-- as many source images as you would like -->
    <button id='replace'>Replace</button>
    <img src='destination-img-1.jpg' class='d'>
    <!-- as many destination images as you have source images -->
    

    JavaScript:

    var r = document.getElementById('replace');
    
    r.addEventListener('click', function(){
      var s = document.querySelectorAll('.s'),
          d = document.querySelectorAll('.d'), 
          l = s.length;
      if(d.length != l) return;
      for(var i = 0; i < l; i++) d[i].src = s[i].src;
    }, false);
    

    Also, use a CSS stylesheet, don't use inline styles.