1

I am making a site with a popup. The popup is supposed to have up to 12 images in it. I am calling my images pizza1.jpg, pizza2.jpg, pizza3.jpg, and so on.

Is there any way with pure JavaScript to make the images show up only if there is actually a file with the name I have told it to look for?

This Question is similar, but all the answers are complicated, and only moderately related.

Community
  • 1
  • 1
  • are you fetching them via AJAX? – Jacob Brazeal May 14 '16 at 21:41
  • Please check the answer there and if image does not exist, than do not show it. If you need further assistance, try to be more accurate, add some code. – skobaljic May 14 '16 at 21:44
  • The other question's answers are only complex solutions to a problem much more complicated than mine. The accepted answer to this question is simple for my situation. – That One Actor May 14 '16 at 21:58

3 Answers3

5

You can use onError event for remove object from your popup:

<img src="src" onError="removeElement(this);" />

Check if it will work:

function removeElement(element) {
     element.remove();
}
Marek Woźniak
  • 1,766
  • 16
  • 34
1

You should handle the onerror event of the img element.

pomber
  • 23,132
  • 10
  • 81
  • 94
1

You can create an Image instance and use its onload event to see if it has loaded. If so just append the image to whatever element.

Demo

var imgurls = [
  "https://placekitten.com/g/64/64",
  "https://placekitten.com/g/32/32",
  "https://placekitten.com/g/none/200",
  "https://placekitten.com/g/100/100",
  "https://placekitten.com/g/24/24"
];

imgurls.forEach(function(url){
  let img = new Image();
  img.onload = onImageLoad;
  img.src = url;
});
  
function onImageLoad(){
  document.body.appendChild(this);
}
<div id="container">
  
</div>
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87