PLaying two videos in sequence in Chrome by using the <video> tag

Frankie &#39;Moodurian&#39; Kam picture Frankie 'Moodurian' Kam · Nov 4, 2011 · Viewed 8.2k times · Source

How do I play two videos in a sequence in the HTML5 video tag?

In Google Chrome, the following code plays only the first intro video.

<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>

var i = 0;
var sources = ['1.mp4', '2.mp4'];
videoElement.addEventListener('ended', function(){
   videoElement.src = sources[(++i)%sources.length];
   videoElement.load();
   videoElement.play();
}, true);

</script>

</head>
<body>
<video id="videoElement" width="640" height="360" autoplay="autoplay">
    <source src="intro.mp4" type="video/mp4"></source>
</video>

<body>
<html>

Answer

ExpExc picture ExpExc · Nov 8, 2011

Browser should fire error 'videoElement is not defined' with your JavaScript code, you must get video element from DOM instead of using its id directly. Please change your code to

$(document).ready(function() {
    //place code inside jQuery ready event handler 
    //to ensure videoElement is available
    var i = 0;
    var sources = ['1.mp4', '2.mp4'];
    $('#videoElement').bind('ended', function() {
        //'this' is the DOM video element
        this.src = sources[i++ % sources.length];
        this.load();
        this.play();
    });
});