Piyush Shrivastava
Piyush Shrivastava

Reputation: 1098

Cannot show a html5 video dynamically with js

I have a table which looks like this:

+------------+---------+
|    Name    |  View   |
+------------+---------+
| 1.mp4      |    X    |
| 2.mp4      |    X    |
+------------+---------+

X are view buttons.

When the user clicks on any of the view button, I want to show the corresponding video in a modal. I am using html5 video tag for that. In the video tag, I want to provide the src dynamically.

The src would be name of the video. I am using javascript for this.

HTML:

the X button:

<a data-toggle="modal" data-id={{name}} href="#Modal" class="preview">X</a>
<!--{{name}} is 1.mp4-->

modal:

...
<div class="modal-body">
<video width="548" height="455" controls>
<source id="vsrc" type="video/mp4">
Your browser does not support video playback.
</video>
</div>
...

JS:

var videoName = $(this).data('id'); //This is correct
document.getElementById('vsrc').src = videoName; 

When I check the source code of the page, the src is correctly set,

<source id="vsrc" type="video/mp4" src="1.mp4">

But there is no video shown on the page, only an empty container and some disabled video control buttons are displayed.

I tried pasting this source code into the actual HTML page and it worked that way, I can't figure out why it doesn't work dynamically.

Upvotes: 1

Views: 583

Answers (1)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Set the video source directly like this...

var vid = document.getElementById('vid');

vid.src = "http://clips.vorwaerts-gmbh.de/VfE_html5.mp4";
vid.play();
<div class="modal-body">
    <video id="vid" width="548" height="455" controls>
    Your browser does not support video playback.
    </video>
</div>

Upvotes: 2

Related Questions