Sharavnan Kv Sharavnan Kv - 2 months ago 7
Javascript Question

Change video source after the first video ends

I have two video files in my design. The first one is logo reveal animation and the second one is logo animation. I want to load the first video only when the page loads every time. And i want to load the second video after the first video ends.

Here my target is: 1st video plays when the page loads(only one time - every page load). If the first video ends, the second video will plays in the loop. I don't want to show the logo reveal(1st) again and again. How to do this. Hope i'll be getting the solution.

Here are the code i have.

HTML :

<video width="400" controls id="myVideo" autoplay>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>


JS

document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler(e) {
alert();
var videoFile = 'https://static.videezy.com/system/resources/previews/000/002/165/original/Black-cat-in-green-grass.mp4';
$(' #myVideo source').attr('src', videoFile);
$("#myVideo")[0].load();
}


Demo : https://jsfiddle.net/jLa1s62w/

Answer

You almost got it.

document.getElementById('myVideo').addEventListener('ended', myHandler, false);

function myHandler(e) {
    alert();
    var videoFile = 'https://static.videezy.com/system/resources/previews/000/002/165/original/Black-cat-in-green-grass.mp4';
    $(' #myVideo source').attr('src', videoFile);
    $('#myVideo').attr("loop", true); /* 1 */
    $("#myVideo")[0].load();
    document.getElementById('myVideo').removeEventListener('ended', myHandler, false) /* 2 */
}

1) Loop attribute so the second video loops.

2) Remove event listener so the video isn't replaced again.

https://jsfiddle.net/yuriy636/jLa1s62w/1/

Note: If you are using jQuery, you can also use jQuery's event method: $('#myVideo').on('ended',myHandler) and $('#myVideo').off('ended',myHandler)

Comments