Skip to content Skip to sidebar Skip to footer

How To Display Images From A JavaScript Array/object? Starting With The First Image Then Onclick To The Next

Attempting to load images from my JavaScript array and display the first one the array. I then need to add a function that will allow the next image in the array to be displayed an

Solution 1:

See I did it like bellow

<script>
    var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
    var index = 0;

    function buildImage() {
      var img = document.createElement('img')
      img.src = images[index];
      document.getElementById('content').appendChild(img);
    }

    function changeImage(){
      var img = document.getElementById('content').getElementsByTagName('img')[0]
      index++;
      index = index % images.length; // This is for if this is the last image then goto first image
      img.src = images[index];
    }
</script>

<body onload="buildImage();">
    <div class="contents" id="content"></div>
    <button onclick="changeImage()">NextImage</button>
</body>

I was not sure div has an onload event or not so I called onload of body.

DEMO


Solution 2:

// the container
var container = document.getElementById('content');
for (var i = 0; i < images.length; i++) {
    // create the image element
    var imageElement = document.createElement('img');
    imageElement.setAttribute('src', images[i]);

    // append the element to the container
    container.appendChild(imageElement);
}

For more information on how to perform DOM manipulation/creation, read up on MDN and other resources. Those will help a lot in your development.

JSFiddle


Solution 3:

    <body>
<img id="thepic"/>
<input type="button" id="thebutt" value="see next"/>
<script>
(function (){
        var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
        var imgcnt = 1;
        function changeIt() {
          if(imgcnt<images.length){
          document.getElementById("thepic").src=images[imgcnt++];
          } else{
          console.log("done")
          }
        }

        document.getElementById("thepic").src=images[0];
        document.getElementById("thebutt").onclick=changeIt;

        })();
        </script>
</body>

Post a Comment for "How To Display Images From A JavaScript Array/object? Starting With The First Image Then Onclick To The Next"