0

I want to put image src into my code. This is my JavaScript code so far:

<script>
    function images(){
        var randomizer = Math.floor((Math.random() * 5)
        var pictures =["images1.jpg","images2","images3.jpg","images4.png","images5.jpg"]
    }
</script>

and this is my HTML code:

<img  id = "bubbles" src="images1.jpg" width="20%" alt = "pics">
<img id = "bubbles2" src="images2.jpg" width="20%" alt= "pics">

The problem that I am facing is that I am not able to put the arrayed string into the src.

3
  • side note : recommend not to have spaces around = Commented Aug 11, 2015 at 2:34
  • Are you hoping to generate the image tags with the javascript array images? Or would you like to update the same image tag with a random image at a set interval? What is your aim? Commented Aug 11, 2015 at 2:34
  • i am trying to like update the value of the src so it will be a random image from the array every time it loads Commented Aug 12, 2015 at 5:21

1 Answer 1

2

The problem is that the src attribute of an image tag can't take in an array of images. You'll need a separate image tag for your photos.

var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];

for (var i = 0; i < pictures.length; i++) {
    var imgEl = document.getElementById("bubbles");
    imgEl.setAttribute("src", imEl[i]);
}

The above code will update the src attribute with the images in the array. However, this will probably so quick you'll only see the last one. You would need to figure out a timing mechanism or integrate your random number function to chose a random image.

Using Math.random()

var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];
var randomizer = Math.floor(Math.random() * 5);
var imgEl = document.getElementById("bubbles");
imgEl.setAttribute("src", imEl[randomizer]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.