user1352096
user1352096

Reputation: 21

How to dynamically replace HTML5 Video src

I've got a project where I've got several videos that I'd like to dynamically load into the page. my HTML is fairly simple a single video tag

<video controls preload width="520" height="350" id="video">
<source src="videos/video0.mp4" type="video/mp4" id="video_source">
</video>

<div id="playlist">
    <a href="videos/video1.mp4">Video File Tomorrow</a>
    <a href="videos/video2.mp4">Video File Tomorrow</a>             
</div>

I'm only using an MP4 file because this project only needs to function in Safari. I've tried 2 JS solutions and both seem to generate separate issues

Solution 1

$("#playlist a").click(function(){
   var video_source_link=$(this).attr("href");
   document.getElementById("video_source").setAttribute("src",video_source_link);
   document.getElementById("video").load();
   document.getElementById("video").play();
   return false;
});

In this version JS updates the src attribute of the source tag but does not load the video.

Solution 2

$("#playlist a").click(function(){
       var video_source_link=$(this).attr("href");
       document.getElementById("video_source").setAttribute("src",video_source_link);
       document.getElementById("video_source").load();
       document.getElementById("video_source").play();
       return false;
});

In this version the video loads into a blank window and when I click the back button Safari crashes with the following error WebKit2WebProcess.exe has encountered a problem and needs to close

Upvotes: 2

Views: 6352

Answers (2)

firepunch
firepunch

Reputation: 99

First, check your video_source_link. If you're video_source_linkis correct, I recommend to delete this line document.getElementById("video").play();in soultion 1. Or How about delete controls preload in the video tag? And the follwing code works for me.

HTML

 <video width="320" height="240" autoplay>
   <source id="video_path" src="" type="video/mp4">
 </video>

JS

 $('#video_path').attr('src', 'path');
 $('video').load();

Upvotes: 0

tommy chheng
tommy chheng

Reputation: 9218

Try changing the video tag instead of the inner child source tag:

$("#video")[0].src = $(this).attr("href");

Upvotes: 1

Related Questions