javascripttouchonmouseclick

How to Swap Image for multiple images


I have very little knowledge of programming. I found this great little bit of javascript that allows you to click the mouse on an image which will cause it to load another in its place and another click to return to original image, this as a bonus also works well when displayed on a touch devices browser. I was going to use it to display before and after photographs. But the code only allows for a single image to be displayed on screen. Can anyone help me by explaining or providing the code to be able to display as many images as desired in a vertical fashion on the page, with this behaviour attached to each. Your help would be greatly appreciated.

Here is the code:

</body>
</html>
<SCRIPT LANGUAGE=JavaScript>
intImage = 2;
function swapImage() {
switch (intImage) {
 case 1:
   IMG1.src = "http://www.danhero.com/riggs1.jpg"
   intImage = 2
   return(false);
case 2:
   IMG1.src = "http://www.danhero.com/riggs2.jpg"
   intImage = 1
   return(false);
 }
}
</SCRIPT>
</HEAD>
<BODY><center>
<IMG id="IMG1" name="IMG1" src="http://www.danhero.com/riggs1.jpg" 
 onclick="swapImage();">
</BODY>
</HTML>

Solution

  • <!doctype html>
    <html>
    <head>
    <style>
    #place img {
        display: block;
        margin: 10px 0;
    }
    </style>
    </head>
    <body>
    <div id="place">
    </div>
    <script>
    var p = document.getElementById('place');
    var images = [
        ["http://www.danhero.com/riggs1.jpg", "http://www.danhero.com/riggs2.jpg"],
        ["http://www.danhero.com/riggs1.jpg", "http://www.danhero.com/riggs2.jpg"]
    ];
    
    function swapImage() {
        var id = +this.id.substring(3);
        if(this.src === images[id][0]) this.src = images[id][1];
        else this.src = images[id][0];
    }
    
    for(var i = 0, l = images.length; i < l; ++i) {
        var dt = document.createElement('img');
        dt.setAttribute('id', 'img' + i);
        dt.setAttribute('src', images[i][0]);
        dt.onclick = swapImage;
        p.appendChild(dt);
    }
    </script>
    </body>
    </html>
    

    The code works in that way:

    During page load the empty div with id "place" is populated with images from array "images".

    This variable is array with two links per image, first will be displayed and second used to swap images. There is no counter, image is checked for its source (src) and if it matches with first element in array then it swaps image for second and vice versa.

    Images have id = "img" + i, where i is a counter (img0, img1, img2 and so on).

    On touchscreens I havent checked but this should fall into click event which is supported even on iPhone with touch events.