-2

I know I can detect an error like this..

img.onerror = function() {
    console.log('error');
}

But is there a way to make something happen only if no errors were found?

EDIT: specifically I'm trying to link an img from a different source

  var img = new Image();
  img.src = 'link';

is there a way to detect if the link is found then append it to body ONLY if it's found?

Magdi Gamal
  • 681
  • 1
  • 9
  • 25

1 Answers1

0

If you want to confirm that the image exist first before loading it to the body, you could do something like this with jquery

var image_url = "https://www.google.co.nz/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" ;

$('<img src="'+ image_url +'">').load(function() {
  alert("image found")
  $(this).appendTo('#testDivID');
}).fail(function() { 
    alert("image not found")
});;

Here is a JS fiddle URL: https://jsfiddle.net/cmd939p4/

H H
  • 366
  • 1
  • 6
  • Updated the answer to only show the image if it is found. I also supplied a jsfiddle example. – H H Nov 28 '17 at 20:10