Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Javascript - Array of Images, How to?

  • 11-07-2014 11:13AM
    #1
    Registered Users, Registered Users 2 Posts: 978 ✭✭✭


    Hi,

    I'm very new to this so please excuse any amateurish mistakes!

    So I have a basic HTML page and this is a snippet from it. All this section does is display an image.

    [HTML]<section>
    <img src="image.jpg" id="displayImage">
    </section>[/HTML]


    I want to create an array of images, so I can change the image on the HTML page by referring to the array. I have just created one item so far for test purposes.
    var arrayOfImages = [];
    arrayOfImages[0] = new Image();
    arrayOfImages[0].src = "image1.jpg";
    


    So, as far as I'm aware the above should all be ok. What I really want to know is how to change the image in the HTML. I have been looking around and have tried a few things to no avail.

    This is a sample of the code I've tried but it doesn't work. I'm not sure if this really makes that much sense.
    document.getElementById("displayImage").src = arrayOfImages[0].src;
    

    As I said I'm new to this so any guidance would be greatly appreciated.


Comments

  • Closed Accounts Posts: 7,967 ✭✭✭Synode


    Use a recursive function. Here's some code I used for a project a few years ago:
    var ImageArr1 = new Array("Trophy.jpg","NZChamp.jpg","IrlAus.jpg","IrlAus.jpg","Statdium.jpg");
      
      function RotateImages(Start)
      {
      	var a = "ImageArr1";
      	var b = document.getElementById('Rotating1');
      	if(Start>=5)
      		Start=0;
      	b.src = "RotatingImages/" + ImageArr1[Start];
      	window.setTimeout("RotateImages("+(Start+1)+")",5000);
      }
    

    Here's the code from the HTML page
    <div class="imageBox">
    
    	<h3>Image Gallery</h3>
    
    	<img src="RotatingImages/Trophy.jpg" id="Rotating1" alt="Image Gallery" />
    
    	<script type="text/javascript">
    		RotateImages(0);
    	</script>
    </div>
    


  • Registered Users, Registered Users 2 Posts: 978 ✭✭✭MooShop


    Ah, I see. I was trying to create an array with the images in each location. Looking at yours, you just use the image names at each location. I tried this and tweaked my earlier code and it's working now. Thanks a million!


Advertisement