ga-wdi-exercises / project1

[project] GA- Project 1
3 stars 75 forks source link

Can't add image to array #235

Closed maureenv closed 8 years ago

maureenv commented 8 years ago

Hi, I'm trying to find a way to attach my images to an array, this is the code I have so far (I made it in a separate document from my memory game):

    cardArray=[
        {text: "A", image: "images/1.png"},
        {text: "A", image: "images/1.png"},
        {text: "B", image: "images/2.jpg"},
        {text: "B", image: "images/2.jpg"},
        {text: "C", image: "images/3.jpg"},
        {text: "C", image: "images/3.jpg"},
        {text: "D", image: "images/4.jpg"},
        {text: "D", image: "images/4.jpg"},
        {text: "E", image: "images/5.jpg"},
        {text: "E", image: "images/5.jpg"},
        {text: "F", image: "images/6.jpg"},
        {text: "F", image: "images/6.jpg"}  

    ];

    for (var i=0; i<cardArray.length; i++){
        var images=document.createElement("img");
        images.classList.add("image");
        body.appendChild(images);
    }

I've created an image class in css with a set height and width. I want to know if there's code that can attach the images in my cardArray to the newly created image tag. I think I have to target each image in the for loop by using cardArray[i].image but I don't know how to do this.

Thank you

joe-gz commented 8 years ago

It looks like you're super close already! try looking up how to update the "src" attribute of an image tag using javascript. you can probably just use that, and the code you have already (cardArray[i].image) to set it up within that same for loop

maureenv commented 8 years ago

None of my images are in a tag in HTML, or located in the CSS. I just put their source in the cardArray in Javascript and then I wanted to attach them to a newly created image tag in javascript. If I'm doing it this way am I still supposed to update the image "src" because I couldn't find a way to do it that would work with my code.

joe-gz commented 8 years ago

yep you can still do it! try something like:

 for (var i=0; i<cardArray.length; i++){
        var images=document.createElement("img");
        images.classList.add("image");
        images.src = cardArray[i].image
        document.body.appendChild(images);
    }

The idea is that you are creating that img HTML tag within that for loop! so as long as you've done that, you can then modify or add an "src" to it once it's created

maureenv commented 8 years ago

Oh my god that worked! Thank you so much!