Home > OS >  Adding an image to an array
Adding an image to an array

Time:12-07

Im a javascript beginner and this is my first project in school. Im trying to display an image with the title and so on but i just dont know how to add in the images into my array and display them.

const products = [
    { id: 1, title: "title", description: "description", price: 123},
    { id: 2, title: "title B", description: "description B", price: 456 },
    { id: 3, title: "title C", description: "description C", price: 789 },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML  =
            `<div >`  
            `<h2>${product.title}</h2>`  
            `<p>${product.description}</p>`  
            `<p>Pris: <b>${product.price}</b></p>`  
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}

CodePudding user response:

Just add another index that takes in the image source/path as the value, and populates it inside a div, just like how you did for the title/description. For the path of the image you might want to add a relative/absolute path appropriately.

    const products = [
    { id: 1, title: "title", description: "description", price: 123, img: 'images/image1.jpeg'},
    { id: 2, title: "title B", description: "description B", price: 456, img: 'images/image3.jpeg' },
    { id: 3, title: "title C", description: "description C", price: 789, img: 'images/image3.jpeg' },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML  =
            `<div >`  
            `<h2>${product.title}</h2>`  
            `<p>${product.description}</p>`  
            `<p>Pris: <b>${product.price}</b></p>`  
            `<img src=${product.img} />
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}

CodePudding user response:

  function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML  =
        `<div >`  
        `<h2>${product.title}</h2>`  
        `<p>${product.description}</p>`  
        `<p>Pris: <b>${product.price}</b></p>`  
        `<p><img src="photoUrl.png" alt="photo" /></p>`  
        `<button onclick="addToCart(${product.id})">Buy</button>`;
   }
}
  • Related