Dynamically Load and Play HTML5 video
Asked Answered
I

2

12

I'm trying to load and play a HTML5 video onClick event. But i'm not able to accomplish this :-/

Here's my HTML5:

<div id="divVideo">
    <video id="video" controls width="560">
        <source id="mp4" type="video/mp4" />
    </video>
</div>

<div onclick="loadVideo('Muse-Animals.mp4');">play</div>

Here's my JS:

function loadVideo(id)
{
    var video = document.getElementById('video');
    var mp4 = document.getElementById('mp4');

    mp4.src = "vidz/" + id;

    video.load();
    video.play();
}

I checked the element and it does update the video tag properties, but doesn't load or play the video.

What am i doing wrong?

Imparipinnate answered 9/9, 2013 at 17:16 Comment(2)
What browser are you using? Not all formats/codecs are supported by all browsers: en.wikipedia.org/wiki/HTML5_videoLiquescent
hi @Liquescent i'm using chrome. but its intended to work on all major browsers (Chrome, Firefox, Safari, IE10 and Opera)Imparipinnate
P
18

First of all check if you are giving the video src static then it is getting played or not. if it is getting played then while giving it dynamically try giving an extra variable in the src to make the video source refresh itself

like

function loadVideo(id)
{
var video = document.getElementById('video');
var mp4 = document.getElementById('mp4');
d = new Date();

mp4.src = "vidz/" + id + d.getTime();

video.load();
video.play();
}
Priggish answered 9/9, 2013 at 17:26 Comment(3)
hi @Rex the video works if i call the loadVideo() function on document ready. but if i try to call the function dynamically it doesn't work. I think the problem is related to the video load :-/ i tried to use you code but it doesn't work, any more suggestions?Imparipinnate
i've got it working! just changed this line in the code mp4.src = "vidz/" + id + "?time=" + d.getTime(); but now i can't get it to autoplay!! :(Imparipinnate
Did you get it to autoplay?Beka
E
0

If you have the video on antoher folder you can try:

function loadVideo(id)
{
    var video = document.getElementById('video');
    var mp4 = document.getElementById('mp4');

    mp4.src = "./vidz/" + id;

    video.load();
    video.play();
}
Enfield answered 25/2, 2024 at 19:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.