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.

3
  • are you fetching them via AJAX? Commented May 14, 2016 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. Commented May 14, 2016 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. Commented May 14, 2016 at 21:58

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should handle the onerror event of the img element.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.