Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Javascript - Array of Images, How to?

  • 11-07-2014 10:13am
    #1
    Registered Users, Registered Users 2 Posts: 974 ✭✭✭


    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: 974 ✭✭✭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