Skip to navigation

Listen to player events

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:

const fpPlayerEl = document.querySelector('fastpix-player');
// Add event listeners
fpPlayerEl.addEventListener('play', function() {
console.log('The video has started playing.');
});
fpPlayerEl.addEventListener('pause', function() {
console.log('The video has been paused.');
});
fpPlayerEl.addEventListener('ended', function() {
console.log('The video has finished playing.');
});

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.


FastPix custom events

Besides the native HTML media events above, the player fires its own events for tracks, quality, chapters, and playlists. Listen for them the same way, with addEventListener.

Track events

EventWhen it firesevent.detail
fastpixtracksreadyAfter the manifest is parsed. May re-emit when subtitle text tracks attach.audioTracks, subtitleTracks, currentAudioTrackLoaded, currentSubtitleLoaded
fastpixaudiochangeWhen the audio track is changed, from the menu or setAudioTrack.tracks, currentId, currentTrack
fastpixsubtitlechangeWhen subtitles are changed, including turning them off.tracks, currentId, currentTrack
fastpixsubtitlecueWhen the active subtitle cue changes.{ text, language, startTime, endTime }

Quality events

EventWhen it firesevent.detail
fastpixqualitylevelsreadyAfter the manifest is parsed. Safe to build a quality menu.{ levels }
fastpixqualitychangeABR switched level, or the user picked one.{ mode, lockedLevel, loadedLevel, previousLoadedLevel }
fastpixqualityfailedAn invalid level id, or a rendition failed to load.{ reason, levelId, raw }

Chapter and playlist events

EventWhen it firesevent.detail
chapterchangeThe active chapter changes.The current chapter.
playbackidchangeThe active playlist item changes.{ playbackId, currentIndex, totalItems }
playlisttoggleThe playlist panel should open or close.{ hasPlaylist, open }

To build a custom track UI around these events, see Build a custom track switcher UI. For the playlist events, see Add a playlist.


Control playback from JavaScript

The player exposes methods for controlling playback from your own code, which is useful for custom controls, Shorts-style UIs, or framework integrations.

MethodWhat it does
play()Starts or resumes playback. Returns a Promise that resolves when playback has started, or rejects if the video is not ready.
pause()Pauses playback.
mute()Mutes the video, and syncs with Chromecast when casting.
unmute()Unmutes the video, sets volume to 1, and syncs with Chromecast when casting.
<fastpix-player id="player" playback-id="your-playback-id"></fastpix-player>
<button onclick="document.getElementById('player').play()">Play</button>
<button onclick="document.getElementById('player').pause()">Pause</button>
<button onclick="document.getElementById('player').mute()">Mute</button>
<button onclick="document.getElementById('player').unmute()">Unmute</button>

For relative seeking from your own controls, use player.seekForward(seconds) and player.seekBackward(seconds). See Build a custom track switcher UI for a full custom-controls example.


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:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/@fastpix/fp-player@latest/dist/player.js"></script>
</head>
<body>
<div class="App">
<fastpix-player
id="fp-player"
playback-id="Your-playback-id">
</fastpix-player>
<p>Current Time: <span id="current-time">0</span> / <span id="duration">0</span> sec</p>
<progress id="progress-bar" value="0" max="100"></progress>
</div>
<script>
const player = document.getElementById('fp-player');
const currentTimeDisplay = document.getElementById('current-time');
const durationDisplay = document.getElementById('duration');
const progressBar = document.getElementById('progress-bar');
// Ensure the player is ready before adding listeners
player.addEventListener('loadedmetadata', () => {
durationDisplay.textContent = Math.floor(player.duration);
});
// Track playback progress
player.addEventListener('timeupdate', () => {
const currentTime = Math.floor(player.currentTime);
const duration = player.duration;
currentTimeDisplay.textContent = currentTime;
if (duration) {
const progressPercent = (currentTime / duration) * 100;
progressBar.value = progressPercent;
}
});
// Optional: Trigger actions at specific times
player.addEventListener('timeupdate', () => {
if (Math.floor(player.currentTime) === 10) {
console.log("Reached 10 seconds!");
}
});
</script>
</body>
</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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/@fastpix/fp-player@latest/dist/player.js"></script>
</head>
<body>
<div class="App">
<fastpix-player playback-id="Some invalid playback Id"></fastpix-player>
<p id="error-message">Error Message:</p>
</div>
<script>
const fpPlayerEl = document.querySelector('fastpix-player');
const errorMessage = document.getElementById('error-message');
// Listen for the error event
fpPlayerEl.addEventListener('error', function(event) {
console.log("Error event received:", event.detail);
if (!event.detail) {
errorMessage.textContent = "An unknown error occurred.";
return;
}
const errorCode = event.detail.code; // Extract the error code properly
switch (errorCode) {
case 1:
errorMessage.textContent = "Video loading was aborted.";
break;
case 2:
errorMessage.textContent = "A network error caused the video to fail.";
break;
case 3:
errorMessage.textContent = "The video file is corrupt or unsupported.";
break;
case 4:
errorMessage.textContent = "The video format is not supported.";
break;
default:
errorMessage.textContent = "An unknown error occurred during video playback.";
break;
}
});
// Optional: Simulate an error event (For testing purposes)
setTimeout(() => {
const errorEvent = new CustomEvent('error', {
detail: { code: 3 } // Simulating "The video file is corrupt or unsupported."
});
fpPlayerEl.dispatchEvent(errorEvent);
}, 2000); // Wait for 2 seconds before dispatching
</script>
</body>
</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.