Search code examples
jquerybuttonvideovideo.jsforward

How to set videojs currentTime for each video


For a client I need to make a functional video playlist with 3 video's. I got them playing separately already, but now I need to make a custom skip button. I tried several things, but I keep getting a Console error "el.currentTime is not a function", "this.currentTime is not a function".

I tried to find some solutions on other forms, but everybody is actually making video players with id's. I want to prevent that to keep my code flexible.

$('video').each(function (i, el) {
    var p = $(el).parent();

        $('.forward-btn', p).click(function () {
            console.log("this video is skipped 5 seconds in" + el);
            el.currentTime(el.currentTime() + 10);
        });

    });
});

Solution

  • The problem you're running into here is that you're not actually initializing Videojs on these players, so you're not working with a reference to a Videojs instance, just a video tag.

    You could either pass the video tag reference to a videojs constructor before using those methods, or use the native HTML5 currentTime attribute setter instead.

    // If you want to use the Videojs methods:
    $('video').each(function (i, el) {
      var vjsEl = videojs(el);
      // ...
    });
    
    // Or, you can keep things as is and just use the `currentTime` attribute directly
    console.log("this video is skipped 5 seconds in" + el);
    el.currentTime = el.currentTime + 10; // notice this isn't a function.
    

    If you go the Videojs constructor route, also keep in mind you'll need to make sure you clean up players (dispose) before removing the video tags from the DOM.

    For what it's worth, just in case you haven't come across it, there's a well-maintained videojs-playlist plugin. You're going to need to keep in mind the performance impact of using multiple video tags + Videojs instances like this (particularly for a large playlist), so at the very least you might want to take a look at their implementation.