2

I'm using the following code to set background-image thumbnails as placeholders for embedded youtube videos. If the video is removed the thumbnail becomes youtube's default 404 thumbnail. I'd like to set my own 404 thumbnail, but I'm not sure how. I can find ways to check for img errors but not for background-image errors. (Also, I can't look for divs with no background-image because they will all have one, it just might be a broken link.)

Anyone know how to check for a broken background-image url?

$(function(){ 

    // VIDEO LOAD

        var videoLinks = {};

        function clickVideo() {
            // trim off img-
            var postId = $(this).attr("id").substr(4);
            if (videoLinks[postId]) {
                $("#" + postId).html(videoLinks[postId]);
            }
        }

        function storeVideo() {
            var videoDiv = this;
            var postId = $(videoDiv).attr("id");
            var code = $(videoDiv).attr("videohtml");
            $(videoDiv).removeClass("videoNoThumbnail");
            var re = new RegExp("(.*/embed/([a-zA-Z0-9_-]+)\\?)(.*)", "m");
            var match = code.match(re);

            if (match) {
                code = match[1] + "autoplay=1&" + match[3];
                var videoId = match[2];
                var div = $("<div class=videoThumbnail />");
                div.css("background-image",
"url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");



                var img = $("<img src=http://dinakelberman.com/play.png class=playButton />");
                img.attr("id", "img-" + postId);
                img.click(clickVideo);
                div.append(img);
//                two.empty();
                $(videoDiv).append(div);
            }
            videoLinks[postId] = code;

        }

        function updateVideos() {
            $('div.videoNoThumbnail').each(storeVideo);

            setTimeout(updateVideos, 200);
        }

        updateVideos();

})
milpool
  • 1,141
  • 10
  • 18

1 Answers1

0

This could be accomplished by loading the thumbnail image with an ajax request: when Youtube serves the 404 thumbnail, it actually responds with a 404 status.

$.get('http://img.youtube.com/vi/' + videoId + '/0.jpg')
.success(function(d){
    // video not removed: set thumbnail
    div.css("background-image","url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");   
})
.error(function(d){
    // video removed: set your own thumbnail
});

The successful case can be further tweaked: the code I wrote load the same image twice (first with the ajax request and later when you set the background image). You could actually use the image loaded with the ajax request, converting the response data to a data-uri image background.

However, to do this you need to request the image using a binary transport for jQuery (or do it with standard XMLHttpRequest) and convert the data to base64.

Community
  • 1
  • 1
dipanda
  • 760
  • 1
  • 11
  • 24