javascript - Switching sources after html5 video has ended -


i know should straight forward if use onended event, this:

  <video src="video.ogv" id="myvideo">   </video>  <script type='text/javascript'>     document.getelementbyid('myvideo').addeventlistener('ended',myhandler,false);     function myhandler(e) {         // want after event     } </script> 

however, ended event firing evn after switch tracks. using videojs player.

in particular case, i'm looking play clip b, , moment finishes, switch clip c.

here code looks like:

// clipa playing...... // user hits button calls switchvideo();  // video = videojs('video-player'); var switchvideo = function (clipb, clipc) {     video.src(clipb);     video.play();      // when clipb has ended...     video.ended(function () {         console.log("clipb ended");         video.src(clipc);         video.play();     }) }; 

the moment call function, can see jumps clipb moment, onended event fired, , video feed jumps clipc. how can ignore first onended event clipa, , instead listen clipb?

update: here final correct answer looks like:

   // video = videojs('video-player');     var switchvideo = function (clipb, clipc) {         video.src(clipb);         video.play();          // when clipb has ended...         video.one('ended', function () {             console.log("clibb ended");             video.src(clipc);             video.play();         })     }; 

update 2: discovered above code work once. (it called 'one' afterall. in particular case, needed able several times.

i made 1 small change, , use video.on('ended', myfunction) instead of video.one('ended', myfunction). can call many times needed.

i came conclusion after reading this stack overflow response.

"addevent" , "removeevent" replaced "on" , "off" per videojs api. - @lyn headley

final solution:

       // video = videojs('video-player');         var switchvideo = function (clipb, clipc) {             video.src(clipb);             video.play();              // when clipb has ended...             video.on('ended', function () {                 console.log("clibb ended");                 video.src(clipc);                 video.play();             })         }; 

for readers: asker using library called videojs, envelops native js-<video> interface. of which, provides event functions: on, off, one.

the original code created new event listener every time switchvideo called, causing ended callback called multiple times.

the solution use one('ended') instead of ended [equivalent on('ended')]:

video.one('ended', function () {     whatever; }); 

Comments