Reputation: 13
I do not understand what's going on when it comes to creating an img dynamically. This is the code:
const pics = document.querySelector('.gridPics');
eventosListener();
function eventosListener() {
document.addEventListener('DOMContentLoaded', () => {
jsonFile();
});
}
I get the pics from a json file. It works well.
function jsonFile () {
fetch('js/fotos.json')
.then(response => {
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
})
.then(data => {
showPics(data);
})
.catch(function () {
this.dataError = true;
})
}
Function that must create pictures dinamically
function showPics(x) {
x.forEach(element => {
const div = document.createElement('div');
div.classList.add('grid-item');
const imagen = document.createElement('img');
imagen.setAttribute("src", element.name);
imagen.setAttribute("alt", element.desc);
imagen.setAttribute("width", '90%');
div.appendChild(imagen);
pics.appendChild(div);
});
}
HTML file
<section class="fotos">
<div class="gridPics"></div>
</section>
For a while I believed that imgs paths were wrong, but I added a img like this but it does no work either
imagen.src = 'https://i.picsum.photos/id/861/200/300.jpg?hmac=kssNLkcAZTJQKpPCSrGodykV8A6CStZxL7dHvtsVUD0';
Json File
[{
"name" : "./../assets/1.jpeg",
"desc": "imagen1"
},...
}]
The estructure
I do not have any error in the console but I can not see anything.
Upvotes: 0
Views: 36
Reputation: 136124
I suspect your issue is that the data is not coming in as JSON as you're loading it from a plain text file, you can solve this by ensuring they are using JSON.parse
.
The below works (ignoring me having to mock out loading the data) just adding showPics(JSON.parse(data));
const jsonData = "[{\"desc\":\"imagen1\",\"name\":\"https://i.picsum.photos/id/861/200/300.jpg?hmac=kssNLkcAZTJQKpPCSrGodykV8A6CStZxL7dHvtsVUD0\" }]";
const fetch = () => Promise.resolve({ok:true, json:() => Promise.resolve( jsonData)});
const pics = document.querySelector('.gridPics');
eventosListener();
function eventosListener() {
document.addEventListener('DOMContentLoaded', () => {
jsonFile();
});
}
function jsonFile () {
fetch('js/fotos.json')
.then(response => {
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
})
.then(data => {
showPics(JSON.parse(data));
})
.catch(function () {
this.dataError = true;
})
}
function showPics(x) {
x.forEach(element => {
const div = document.createElement('div');
div.classList.add('grid-item');
const imagen = document.createElement('img');
imagen.setAttribute("src", element.name);
imagen.setAttribute("alt", element.desc);
imagen.setAttribute("width", '90%');
div.appendChild(imagen);
pics.appendChild(div);
});
}
<section class="fotos">
<div class="gridPics"></div>
</section>
Upvotes: 2