Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check if a file returns a 404 error if it's on a different server with javascript or jQuery?

Is it possible to check if a file returns a 404 error if it's on a different server using jQuery/javascript?

I'm using the youtube api to get a HD screenshot for the video I'm embedding, but the JSON that it returns gives no indication of whether a HD screenshot for the video exists.

the url for the screenshot is usually, http://img.youtube.com/vi/ + video.ID + /maxresdefault.jpg

but when it doesn't exist, i get this ugly low-res gray POS: http://img.youtube.com/vi/MAyTES9gDAU/maxresdefault.jpg

So, basically, I want to check if the screenshot exists and if not, apply display: none to the div that holds it.

like image 883
andrew nguyen Avatar asked Jul 05 '12 02:07

andrew nguyen


1 Answers

Create an <img> element pointing to that image, then handle the onerror event and hide it.

like image 107
SLaks Avatar answered Oct 16 '22 23:10

SLaks