0

I was looking for a function that checks if the URL is an image or not, and I found this:

function checkImage(imageSrc, good, bad) {
    var img = new Image();
    img.onload = good; 
    img.onerror = bad;
    img.src = imageSrc;
}

checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );

it works alright, but the author did not explain how it works, and I'm a bit baffled,

how does img.onload=good knows what function to activate, and on the other hand img.onerror=bad, how does it work?

thank you for the help!

Alexander
  • 1,288
  • 5
  • 19
  • 38
  • See [`image.onload`](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/image.onload). – Etheryte Apr 27 '19 at 10:59
  • I understand how image.onload works, but why assign them the anonymous functions? – Alexander Apr 27 '19 at 10:59
  • If you check the arguments you are passing functions to alert good or bad based on image events. OnError is returned when image link is not found or broken. OnLoad works when image is loaded or found. If found good function from checkImage argument you passed is triggered or bad. – MJN Apr 27 '19 at 11:00
  • You call your method `checkImage` which was implemented above and you pass those alert messages as callback functions to your method – messerbill Apr 27 '19 at 11:00
  • It's just for checking purpose. You can do anything based on you need like adding class to image or something you wish to do when image is broken etc. It totally depends. This function is just like a example. – MJN Apr 27 '19 at 11:02

1 Answers1

1

He's is basically creating an img element with the attributes src, onload and onerror. The equivalence of this in html would be

<img src="foo.gif" onload="function(){alert('good')}" onerror="function(){alert('bad')}" />
sassy_rog
  • 1,077
  • 12
  • 30