Login

Listening video events in player

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.


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:


<!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.