I was given a prompt to loop through items in a javascript object. Each item has an imageUrl property that points to this url: https://www.placebeard.it/400x400 This url is supposed to generate random images on each visit, but when I loop over the objects I end up getting the same image 25 times. When I inspect the page and click on the images I get random images. This is a codepen project, could that be the problem?
Here is a sample of the code used to get the image
const makeCard = (item) => {
let card = document.createElement('div');
card.classList.add('card', 'p-0');
// card image
let image = document.createElement('img');
image.classList.add('card-img-top');
image.src = `${item.imageUrl}`;
console.log(image.src);
card.appendChild(image);
//... append to container
}
Thanks
CodePudding user response:
This is a trick that your browser plays: because you point the image to the same URL, the browser will think it's the same image. You can get in front of it by adding a dummy query string and a random value, e.g.:
const makeCard = (item) => {
let card = document.createElement('div');
card.classList.add('card', 'p-0');
// card image
let image = document.createElement('img');
image.classList.add('card-img-top');
image.src = `${item.imageUrl}?random=${Math.random()}`; // notice this
console.log(image.src);
card.appendChild(image);
//... append to container
}
And you should get different images (servers usually ignore query strings they don't recognize).
CodePudding user response:
You Can Add Images src in json file and transform the json file to the javascript object and make a loop with images count