Callback Functions for video.js Player


In this tutorial, we'll learn about the various event listeners and how to use them with callback functions for a video.js player. Video.js is a popular, open-source library used for creating video players in browsers. Using video.js you can tweak every single part of a video player without much problems or hassle. Aside from that, video.js provides a plethora of default events like play, pause, playing, loadedmetadata, timeupdate, canplaythrough, loadeddata etc.

So, for the purpose of this tutorial, we're going to learn about the callback functions of various event listeners in video.js. Callback functions are really crucial as they are triggered when a certain event happens. So, we can perform different actions with the help of various callback functions. Now let's move to the following section of the article to understand the various events and their callback functions.

Callback Functions for video.js Player

Callback functions are those functions that are passed as an input argument to another function. However, callback functions are extensively used to continue the execution of code after an async operation like events. Event listeners are functions or methods that are invoked when a specific event is triggered. For example, an event can be playing a video or pausing a video, etc. By making use of the event listeners and callback functions we can achieve our desired functionality.

Basically, the event listeners keep waiting continuously for some user interactions to happen like playing a video, pausing a video then executing the corresponding callback function when the event triggers.

If we talk about video.js specifically, you get a plethora of event listeners which can be used to change the state of a video player. For example, play, pause, resume, etc.

For the purpose of this article, we're going to go through the following events and their callback functions one by one −

  • LoadedData Event

  • LoadedMetaData Event

  • Time Update Event

  • Ended Event Event

Let's quickly have a look at each one of these.

LoadedData Event

The callback function of 'loadeddata' event is triggered when the current frame of a video is loaded. The current frame is usually the first frame of the video. So, when the current frame is loaded but not the next frame, the callback function of the loadeddata event is triggered.

Prerequisite − Assuming that you know how to create a basic video player using the video.js library, let's learn how to capture the 'loadeddata' event using video.js

You can capture 'loadeddata' event by using 'loadeddata' as an input on the reference of your video.js player using the player.on() method. It binds the event and the callback function together. It usually accepts two parameters as input, the first one being the event name (loadeddata in our case) and the second parameter is the callback function which will get invoked as soon as the defined event is triggered. So, callback functions passed to 'loadeddata' event listener are going to be executed whenever the current frame (first frame) of the video player has been loaded.

You can use the following code to capture the 'loadeddata' event and trigger the callback function to alert a text in the browser window −

<script>
   // Initializing the video player
   const player = videojs('my-video-player');

   // loadedData event listener
   player.on('loadeddata', function () {
      window.alert('Video Player Data Loaded');
   });
</script>

In the preceding snippet, we used the 'loadeddata' event listener on our video player reference using the 'player.on()' method to alert 'Video Player Data Loaded' whenever the current frame of the video player is loaded.

Example 1

Here we have showed how the complete example for using loadeddata event listener will look like −

<!DOCTYPE html>
<html>
<head>
   <title>Video.JS CallBack Functions for Video Player</title>

   <!-- Importing Video.js CSS / JS using CDN URL -->
   <link href="https://vjs.zencdn.net/7.19.2/video-js.css" rel="stylesheet" />
   <script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>
</head>
<body>
   <video
      id="my-video-player"
      class="video-js vjs-default-skin vjs-big-play-centered"
      preload="true"
      controls="true"
      fluid="true"
      muted="true"
      autoplay="true"
      poster="assets/sample.png"
      data-setup='{}'
   >
   <source
      src="https://www.tutorialspoint.com/videos/sample720.mp4"
      type="video/mp4"
   >
   </video>
   <script>
      // Initializing the video player
      const player = videojs('my-video-player');

      // loadedData event listener
      player.on('loadeddata', function () {
         window.alert('Video Player Data Loaded');
      });
   </script>
</body>
</html>

We've tried to implement the following things in the above code

  • First, we've used the free CDN URL of video.js to import the required CSS and JS files of video.js in the <head> section of the code.

  • Further, we've created a <video> element inside the <body> section of our code. The <video> element has been initialized with classes like video.js, video-default-skin and vjs-big-play-centered.

  • The 'id' of the video element i.e. 'my-video-player' has been later used in the <script> section of the code to create a video player for this id.

  • We've also utilized some standard HTML video options like controls, muted, and poster for the <video> element.

  • In the <script> tag at the bottom, 'loadeddata' event listener is used to display the 'Video Player Data Loaded' message, using the callback function on the browser window whenever the current frame of our video is loaded.

The execution of the above code is going to create a video player in the browser, which is going to show an alert message on windows when the current frame or the first frame of our video is loaded.

Now that we know how to use the callback function with 'loadeddata' event listener, let's move to the next section of this article to understand the 'loadedmetadata' listener.

LoadedMetaData Event

The callback function of the 'Loadedmetadata' event listener is invoked when the browser has loaded the metadata i.e duration, dimension, text tracks, etc of a video. This listener can be very beneficial when we are loading the video from a URL or third-party API. In those scenarios, we need to wait for the video to be loaded before we make any changes to the player.

For using this listener, we'll need to use 'loadedmetadata'' as input to the video player reference using the 'player.on()' method.

You can use the following code for showing a message whenever the metadata of our video is loaded using the 'loadedmetadata' event with a callback function −

<script>
    // Initializing the video player
    let player = videojs('my-video-player');

    // Loaded Meta Data Event listener
    player.on('loadedmetadata', function () {
      window.alert('Video Player Meta Data Loaded');
    });
</script>

In the above snippet, 'loadedmetadata' event listener has been used to wait till the metadata of a video is loaded before alerting a text. The callback function of this event is invoked even before the 'play' event listener as a video needs to be loaded first before it is played.

Now, let's move on to learn about the callback function of the next event listener.

Time Update Event

The callback function of 'Timeupdate' event listener is one of the most important listeners as it gets triggered every time the video's current playback time is changed. So, as a video is being played, this event gets triggered every 15 250 ms. This callback function on this event can be used with 'timeupdate' as input to the player.on method.

Consider the below snippet for showing a message, when our video has crossed the 15 seconds mark using 'timeupdate' event listener with a callback function −

<script>
    // Initializing the video player
    let player = videojs('my-video-player');

    // Time Update event listener
    let alertShown = false;
    player.on('timeupdate', function () {
      if (player.currentTime() > 15 && !alertShown) {
        window.alert('Video has Played for 15 seconds!');
        alertShown = true;
      }
    });
</script>

In the above snippet, we've used the 'timeupdate' event to alert a text when the video has played for 15 seconds with the help of a callback function. Notice how the currentTime() method is used to get the current time of a video player.

Now, let's move on to the callback function of the ended event listener.

Ended Listener

Callback function of 'Ended' event listener is invoked when our video has ended. It can be used for showing a replay button or playing the next video when the current one has ended. For using this listener, we'll need to use 'ended' as input to the video player reference using the 'player.on()' method.

Let's alert a message when a video ends, using the 'ended' listener with a callback function −

<script>
    // Initializing the video player with video options
    let player = videojs('my-video-player');

   // Ended Event listener
   player.on('ended', function () {
      window.alert('Video Player Ended!');
   });
</script>

In the above snippet, we've used the 'ended' listener to display a text on the window when our current video has finished playing.

Example 2

Adding all the above event listeners to the complete example will look something like this −

<!DOCTYPE html>
<html>
<head>
   <title>Video.JS CallBack Functions for Video Player</title>

   <!-- Importing Video.js CSS / JS using CDN URL -->
   <link href="https://vjs.zencdn.net/7.19.2/video-js.css" rel="stylesheet" />
   <script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>

</head>
<body>
   <video
      id="my-video-player"
      class="video-js vjs-default-skin vjs-big-play-centered"
      preload="true"
      controls="true"
      muted="true"
      autoplay="true"
      fluid="true"
      poster="assets/sample.png"
      data-setup='{ }'
   >
   <source
     src="https://www.tutorialspoint.com/videos/sample720.mp4"
     type="video/mp4"
   >
   </video>
   <script>
      // Initializing the video player with video options
      let player = videojs('my-video-player');

      // loadedData event listener
      player.on('loadeddata', function () {
         window.alert('Video Player Data Loaded');
      });

      // Time Update event listener
      let alertShown = false;
      player.on('timeupdate', function () {
         if (player.currentTime() > 15 && !alertShown) {
            window.alert('Video has Played for 15 seconds!');
            alertShown = true;
         }
      });

      // Loaded Meta Data Event listener
      player.on('loadedmetadata', function () {
         window.alert('Video Player MetaData Loaded');
      });

      // Ended Event listener
      player.on('ended', function () {
         window.alert('Video Player Ended!');
       });
   </script>
</body>
</html>

On execution of the above code, a video player will be created which will display text messages, when the video metadata is loaded, then when the video data is loaded and when the video has ended.

Conclusion

In this tutorial, we understood the callback functions of various event listeners that can be used in a video.js player like loadeddata, laodedmetadata, timeupdate, and ended. We also saw how can we use these listeners with callback functions with the help of fully working examples.

Updated on: 13-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements