Home > Blockchain >  Display Images from JSON Array using JavaScript
Display Images from JSON Array using JavaScript

Time:04-11

I tried to display an image from the image folder in JSON array to Javascript but I am not sure if I am getting the right path. When the click event happens, everything works except for the image is not showing in the <img id "picture">, the picture is not showing up in the img section of my HTML.

I tried to change the path to ../Images/room_1.jpg but it still not working.

FYI: I have a separate folder that stores images, both json and js are stored in the javascript folder. should I put the same image file in the javascript folder?

html

<h2>Select a Hotel</h2>
    <ul class ="hotels">
        <li><a href="#" id="marriott"> Marriott Hotel Rooms</a></li>
    </ul>
<h2 id="hotelName">Hotel</h2>
<h3>Adress: <span id="address"></span></h3>
<img id="picture">   

Hotel.json

{
"hotels": [
    {
        "name": "Marriott",
        "address": "098 hollywood Street",
        "picture": "room_1.jpg"
    }

JS

async function getHotelData() {

    try {

        const response = await fetch('Javascript//hotel.json')
        return await response.json() 

    } catch (error) {
        console.error(error)
    }

}

let hotelData = {}

getHotelData().then(data => hotelData = data)
 

const hotelEvent = document.querySelectorAll("a").forEach(a => {
    a.addEventListener('click', hotelInfo )
})

function hotelInfo(event) {
    let hotelChoice = hotelData.hotels.find(hotel => {
        return event.target.id === hotel.name.toLowerCase()
        return event.target.id === hotel.address.toLowerCase()
        return event.target.id === hotel.picture.toLowerCase()

        
    })
    console.log(hotelChoice)

    document.querySelector("#hotelName").textContent = `${hotelChoice.name} Hotel`
    document.querySelector("#address").textContent = `${hotelChoice.address}`
    document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`



}

CodePudding user response:

You need to set the src property to the image instead of setting its innerHTML.

A normal img tag would look something like this:

<img id="image" src="/path/to/image.png">

You need to replicate the same using JavaScript:

document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`
// Becomes
document.querySelector("#picture").src = `${hotelChoice.picture}`

Also, pay attention to the image path inside the JSON file, it should be relative to the HTML document you're using it, not the JavaScript one. So if your images are stored inside a separate directory you should change the path inside your JSON file accordingly.

Example: If your HTML file is in the project root and there is an images folder, you JSON should be something like:

{
  "hotels": [
    {
      "name": "Something",
      "address": "Some Street, 12",
      "picture": "images/picture_name.jpg"
    }
  ]
}
  • Related