How to make events fire when an HTML video reaches a certain time mark?

I'm wondering whether this is even possible, and if so, how it would be done. So I have an HTML5 video on my page

<video id="ssvid">
      <source src="assets/Cisco_SmartStack_04012016_NoText_2.mp4" type="video/mp4" />
</video>

and let's say I want functions to be invoked at the 2-, 13- and 15-second marks of the video playing. I'm trying to create an object like

$(function(){
    window.VidHandler = (function(divid){
        this.divid = divid;
        this.PauseFunctions = [
            {
                SecondMark: 2,
                OnSlideTo: function () { },
                OnSlideAway: function () { }
            },
            {
                SecondMark: 13,
                OnSlideTo: function () { },
                OnSlideAway: function () { }
            },
            {
                SecondMark: 15,
                OnSlideTo: function () { },
                OnSlideAway: function () { }
            }
        ];
    })("ssvid");
});

but I don't know if JavaScript has an "ontimemark(2)" type of event listener that I can set up. Will I have to create a setInterval to do this?

Answers 1

  • How to make events fire when an HTML video reaches a certain time mark?

    Use currentTime and timeupdate see the demo utilize both.

    but I don't know if JavaScript has an "ontimemark(2)" type of event listener that I can set up.

    timeupdate

    Will I have to create a setInterval to do this?

    No, see Snippet below.

    • Every timeupdate event fires the console.log

    • vidHandler() uses a switch to fire on second marks 2, 13, and 15.

    • You can replace the console.logs with the slide methods.

    • By the looks of it, currentTime looks more like 1sec = 3.5sec? Or the reported duration for the video element is inaccurate.

    Snippet

      var ssvid = document.getElementById('ssvid');
      var tick = ssvid.currentTime;
    
      ssvid.addEventListener('timeupdate', function(e) {
        console.log('currentTime: ' + tick);
        tick++
        vidHandler(tick);
      }, false);
    
    
      function vidHandler(time) {
        switch (time) {
          case 2:
            console.log('2 second mark');
            break;
          case 13:
            console.log('13 second mark');
            break;
          case 15:
            console.log('15 second mark');
            break;
    
          default:
            return false;
        }
      }
    <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    
    <video id="ssvid" controls width="300">
      <source src="http://glpjt.s3.amazonaws.com/so/av/vs34s3.mp4" type="video/mp4" />
    </video>


Related Articles