Just want to ask this (please do note that I am new in programming and only practice during my free time)
I have 10 images saved locally to a folder (named "designImages") within my project folder
How can I display all the images within that folder to an individual div in the HTML using JSON (and javscript if needed)?
I tried fixing this but to no avail. The div just shows a text string in the front end.
JSON format and JS Here is my code (tried to show 1 just to test):
let images = {
id: "1",
name: "Design 1",
imageUrl: "/design-images/1.png",
};
let output = document.getElementById("myImage");
output.innerHTML = images.imageUrl;
HTML
<body>
<div id="myImage">
</body>
Here is my practice website: You can view the problem when you scroll down to the See My Works! section. https://vladesplana.web.app/
CodePudding user response:
Good afternoon,
First, you should close your <div> tag :)
Then, you should add an <img> tag to your HTML. You can do it using HTML but then, you will not be able to auto-add new images inserted in your folder.
I suggest doing the following in javascript:
let myDiv = document.getElementById("myImage");
let img = document.createElement("img");
img.src = images.imageUrl;
myDiv.appendChild(img);
First line gets your div in a variable ; second line creates a new image element ; third line puts the source for your image in it and the last line adds the image element to your html as a child of your div.
I hope this is clear enough to help you fix your code.
All best, Benjamin
CodePudding user response:
Try this,
const images =[ // you have to create 10 objs instead of two
{
id: "1",
name: "Design 1",
imageUrl: "/design-images/1.png",
},{
id: "2",
name: "Design 2",
imageUrl: "/design-images/2.png",
};
]
const imagesOnSingleDiv=images.map(img=> `<img src=${img.imageUrl} alt=${img.name}>`).join("\n")
let output = document.getElementById("myImage");
output.innerHTML=imagesOnSingleDiv
The imagesOnSingleDiv contains the content for the output
