Alexander
Alexander

Reputation: 1378

Image loading function, how does it work?

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!

Upvotes: 0

Views: 73

Answers (1)

sassy_rog
sassy_rog

Reputation: 1097

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')}" />

Upvotes: 1

Related Questions