Algernop K.
Algernop K.

Reputation: 477

Replace video with an image on error

How do I replace a video with an image if the video is missing a source?

<div id="gameImage"><img id="img" src=""></div>
<div id="gameTrailer">
    <video autoplay loop width="960" height="540" id="video">
        <source src="" id="gameTrailer_window">
    </video>
</div>

The source to the video is appended via AJAX like this:

var videoSrc = data.gameTrailer;
var video_block = $('#video');
video_block.load();
$("#video").find("#gameTrailer_window").attr("src", videoSrc)

..but in some cases, var videoSrc will equal null, meaning that no video will show up. So I figured an onError-function displaying an image instead (which will always have a source available) would work, but a video element without source does not seem to be returning an error, therefor the following function:

$("#video").error(function () { 
    $(this).hide(); 
    $("#gameImage").find("#img").attr("src", data.gameImage)
});

..will not fire. It might be something off with the code, I'm not 100% certain.

Any sort of nudge in the right direction will be much appreciated, thanks in advance.

John

Upvotes: 0

Views: 627

Answers (1)

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10187

why don't you check the condition in first function instead of writing another function

if(videoSrc!=null){
  $("#video").find("#gameTrailer_window").attr("src", videoSrc)
} else {
  $("#gameImage").find("#img").attr("src", data.gameImage);
}

If var is not null then video src will change else image src will change.

Upvotes: 2

Related Questions