0
votes

I am trying to load the path to the video file source into the source tags of an html5 video element using jQuery. The video tag is inside a Bootstrap modal and doesn't get loaded until the modal is opened. Setup is something like this:

<video class="video-element" controls>
    <source class="mp4" src="" type="video/mp4">
    <source class="webm" src="" type="video/webm">
    <source class="ogg" src="" type="video/ogg">
    Your browser doesn't support HTML5 video tag.
</video>

Here's the actual problem: I am able to add the source path to the src property in all three source tags. However, the video doesn't appear.

Here's what I've tested and tried.

  • I have removed the 3 <source> tags and added the source path to the src property of the <video> tag directly. Done that way, everything works fine. The video appears and is playable. I did this dynamically using jQuery just like I'm trying to do with the 3 <source> tags.

  • I have added the source path to the src property of the 3 <source> tags statically in the html, not dynamically with jquery. That also works fine and the video plays.

  • I have verified that the path is correct when I add it dynamically to the src properties of the 3 <source> tags.

So for some reason, the video plays when I load the path into the src property of the <video> tag directly and also when I put it statically into the html src property of the 3 <source> tags but not when I load it into the <source> tags dynamically with jQuery.

Any takers?

1

1 Answers

0
votes

I'd probably simplify things and only work with a single src by checking canPlayType and then just loading the relevant source

<video class="video-element" id="video" controls>
    Your browser doesn't support HTML5 video tag.
</video>

<script>
var v = document.getElementById("video")
var vid = "video-file-name" // assumes all videos have the same file prefix, just different extensions
if (v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"') == "probably") {
    vid = vid + ".mp4"
} else if (v.canPlayType('video/webm; codecs="vp8.0, vorbis"') == "probably") {
    vid = vid + ".webm"
} else {
    vid = vid + ".ogg"
}
v.src = vid
</script>