For AI agents: a documentation index is available at the root level at /llms.txt and /llms-full.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
StatusSupportDiscussionsLog inSign Up
Docs HomeAPI ReferenceVideo on DemandAI FeaturesLive StreamingVideo PlayerVideo DataCloud PlayoutRecipes
Docs HomeAPI ReferenceVideo on DemandAI FeaturesLive StreamingVideo PlayerVideo DataCloud PlayoutRecipes
  • Player SDKs
    • Introduction
  • Web player
    • Install the FastPix web player
    • Play uploaded videos
    • Handle playback errors
      • Autoplay, loop, and mute
      • Control playback speed
      • Set the volume preference
      • Control playback resolution
      • Set the playback start point
      • Set the seek duration
      • Manage audio and subtitles
      • Add seek preview thumbnails
      • Add chapters to the video timeline
      • Listen to player events
      • Cast to Chromecast (Beta)
  • Android player
    • Install FastPix Android player
    • Set up the player
    • Play uploaded videos
    • Handle playback errors
  • iOS player
    • Install FastPix iOS player
    • Play uploaded videos
    • Handle playback errors
  • Flutter player
    • Install FastPix Flutter player
    • Play uploaded videos
    • Handle playback errors
LogoLogo
StatusSupportDiscussionsLog inSign Up
On this page
  • Why listen to video events?
  • How to make the player listen to events
  • Example 1: Tracking playback progress
  • Example 2: Error handling with the error event
Web playerPlayback

Listen to player events

Was this page helpful?
Previous

Cast to Chromecast (Beta)

Next
Built with

Track and respond to FastPix player events, such as play, pause, seek, buffering, and completion, to monitor playback and improve interactivity.

By listening to events, you can track key moments like when a video starts, pauses, ends, or encounters an error. This capability is particularly useful for triggering additional actions or analytics during playback. In this guide, we’ll walk through how you can use this feature, followed by two practical examples.


Why listen to video events?

The HTML <video> element triggers various media events throughout its lifecycle, such as:

  • play: When the video starts playing.
  • pause: When the video is paused.
  • ended: Triggered when the video playback is complete.
  • timeupdate: Periodically trigerred as the video plays, giving updates on the current time.
  • error: Fired when the video encounters a playback issue.

By having fastpix-player listen to these events, you gain access to detailed control over video playback, enabling you to:

  • Handle errors gracefully by displaying user-friendly messages or troubleshooting advice.
  • Create engaging, interactive experiences by responding to specific moments in the video.

How to make the player listen to events

To listen for video events in the player, you can use the addEventListener() method. This method allows you to listen for events on the video element and execute custom JavaScript functions when these events are triggered.

Here’s a basic example of setting up event listeners for play, pause, and ended events:

1const fpPlayerEl = document.querySelector('fastpix-player');
2
3// Add event listeners
4fpPlayerEl.addEventListener('play', function() {
5 console.log('The video has started playing.');
6});
7
8fpPlayerEl.addEventListener('pause', function() {
9 console.log('The video has been paused.');
10});
11
12fpPlayerEl.addEventListener('ended', function() {
13 console.log('The video has finished playing.');
14});

In this example, the querySelector() method is used to locate the underlying <video> element inside the fastpix-player element, enabling event listeners to be attached.


Example 1: Tracking playback progress

The timeupdate event is useful for tracking video progress in real-time, such as updating a custom progress bar or triggering certain actions at specific times. Here’s how you can set up a listener to update the playback progress dynamically:


1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Document</title>
7 <script src="https://cdn.jsdelivr.net/npm/@fastpix/fp-player@latest/dist/player.js"></script>
8</head>
9<body>
10 <div class="App">
11 <fastpix-player
12 id="fp-player"
13 playback-id="Your-playback-id">
14 </fastpix-player>
15
16 <p>Current Time: <span id="current-time">0</span> / <span id="duration">0</span> sec</p>
17 <progress id="progress-bar" value="0" max="100"></progress>
18 </div>
19
20 <script>
21 const player = document.getElementById('fp-player');
22 const currentTimeDisplay = document.getElementById('current-time');
23 const durationDisplay = document.getElementById('duration');
24 const progressBar = document.getElementById('progress-bar');
25
26 // Ensure the player is ready before adding listeners
27 player.addEventListener('loadedmetadata', () => {
28 durationDisplay.textContent = Math.floor(player.duration);
29 });
30
31 // Track playback progress
32 player.addEventListener('timeupdate', () => {
33 const currentTime = Math.floor(player.currentTime);
34 const duration = player.duration;
35
36 currentTimeDisplay.textContent = currentTime;
37
38 if (duration) {
39 const progressPercent = (currentTime / duration) * 100;
40 progressBar.value = progressPercent;
41 }
42 });
43
44 // Optional: Trigger actions at specific times
45 player.addEventListener('timeupdate', () => {
46 if (Math.floor(player.currentTime) === 10) {
47 console.log("Reached 10 seconds!");
48 }
49 });
50 </script>
51</body>
52</html>


Example 2: Error handling with the error event

Playback errors can occur due to network issues, unsupported formats, or other reasons. By listening to the error event, you can display user-friendly error messages and guide users through potential solutions:


HTML
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Document</title>
7 <script src="https://cdn.jsdelivr.net/npm/@fastpix/fp-player@latest/dist/player.js"></script>
8</head>
9<body>
10 <div class="App">
11 <fastpix-player playback-id="Some invalid playback Id"></fastpix-player>
12 <p id="error-message">Error Message:</p>
13 </div>
14
15 <script>
16 const fpPlayerEl = document.querySelector('fastpix-player');
17 const errorMessage = document.getElementById('error-message');
18
19 // Listen for the error event
20 fpPlayerEl.addEventListener('error', function(event) {
21 console.log("Error event received:", event.detail);
22
23 if (!event.detail) {
24 errorMessage.textContent = "An unknown error occurred.";
25 return;
26 }
27
28 const errorCode = event.detail.code; // Extract the error code properly
29
30 switch (errorCode) {
31 case 1:
32 errorMessage.textContent = "Video loading was aborted.";
33 break;
34 case 2:
35 errorMessage.textContent = "A network error caused the video to fail.";
36 break;
37 case 3:
38 errorMessage.textContent = "The video file is corrupt or unsupported.";
39 break;
40 case 4:
41 errorMessage.textContent = "The video format is not supported.";
42 break;
43 default:
44 errorMessage.textContent = "An unknown error occurred during video playback.";
45 break;
46 }
47 });
48
49 // Optional: Simulate an error event (For testing purposes)
50 setTimeout(() => {
51 const errorEvent = new CustomEvent('error', {
52 detail: { code: 3 } // Simulating "The video file is corrupt or unsupported."
53 });
54 fpPlayerEl.dispatchEvent(errorEvent);
55 }, 2000); // Wait for 2 seconds before dispatching
56 </script>
57</body>
58</html>

Explanation:

  • errorevent: This event fires when a video playback issue arises, such as an unsupported format or network error.
  • Custom error handling: The error object contains a code property that helps identify the type of problem. This example uses the code to display relevant error messages, improving the user experience by making issues clearer.