JavaScript Document cuechange Event: The Complete Guide

JavaScript is packed with events that help us make our web pages interactive. One of these events is the cuechange event. This guide will explain everything you need to know about it. We will cover what it is, why it’s useful, where to use it, how to implement it, and when it comes into play. Let’s get started!

What is the cuechange Event?

The cuechange event is an event that fires when a new cue becomes active in a text track, or when a cue becomes inactive. Text tracks are used for subtitles, captions, descriptions, chapters, or metadata in video and audio elements.

Why Use the cuechange Event?

The cuechange event is useful for handling changes in text tracks. It allows you to perform actions when cues change, such as updating subtitles, showing descriptions, or handling custom events based on metadata.

Where Can You Use the cuechange Event?

You can use the cuechange event with any HTML media element that supports text tracks, such as <audio> and <video>. This event is particularly useful for enhancing user experience with interactive media content.

How to Use the cuechange Event

Let’s dive into some examples to see how the cuechange event works in different scenarios.

Basic Example

Here’s a simple example to show how the cuechange event works with a video element.

HTML
<video id="myVideo" controls>
  <source src="movie.mp4" type="video/mp4" />
  <track id="myTrack" kind="subtitles" src="subtitles.vtt" srclang="en" label="English" />
  Your browser does not support the video tag.
</video>

<p id="cueDisplay">Current cue: None πŸŽ₯</p>

<script>
  const video = document.getElementById("myVideo");
  const track = document.getElementById("myTrack").track;
  const cueDisplay = document.getElementById("cueDisplay");

  track.addEventListener("cuechange", () => {
    const activeCues = track.activeCues;
    if (activeCues.length > 0) {
      cueDisplay.textContent = `Current cue: ${activeCues[0].text} πŸŽ₯`;
    } else {
      cueDisplay.textContent = "Current cue: None πŸŽ₯";
    }
  });
</script>

In this example, when the subtitles change, the new cue is displayed in a paragraph.

Example with Multiple Tracks

Let’s see a more advanced example where we handle multiple text tracks.

HTML
<video id="myVideo" controls>
  <source src="movie.mp4" type="video/mp4" />
  <track id="subTrack" kind="subtitles" src="subtitles.vtt" srclang="en" label="English" />
  <track id="descTrack" kind="descriptions" src="descriptions.vtt" srclang="en" label="Descriptions" />
  Your browser does not support the video tag.
</video>

<p id="subDisplay">Current subtitle: None 🎬</p>
<p id="descDisplay">Current description: None πŸ“–</p>

<script>
  const video = document.getElementById("myVideo");
  const subTrack = document.getElementById("subTrack").track;
  const descTrack = document.getElementById("descTrack").track;
  const subDisplay = document.getElementById("subDisplay");
  const descDisplay = document.getElementById("descDisplay");

  subTrack.addEventListener("cuechange", () => {
    const activeCues = subTrack.activeCues;
    if (activeCues.length > 0) {
      subDisplay.textContent = `Current subtitle: ${activeCues[0].text} 🎬`;
    } else {
      subDisplay.textContent = "Current subtitle: None 🎬";
    }
  });

  descTrack.addEventListener("cuechange", () => {
    const activeCues = descTrack.activeCues;
    if (activeCues.length > 0) {
      descDisplay.textContent = `Current description: ${activeCues[0].text} πŸ“–`;
    } else {
      descDisplay.textContent = "Current description: None πŸ“–";
    }
  });
</script>

In this example, we have both subtitles and descriptions, each with its own display that updates when the cue changes.

Example with Metadata Track

Let’s see how the cuechange event works with a metadata track, which can be used for custom events.

HTML
<video id="myVideo" controls>
  <source src="movie.mp4" type="video/mp4" />
  <track id="metaTrack" kind="metadata" src="metadata.vtt" srclang="en" label="Metadata" />
  Your browser does not support the video tag.
</video>

<p id="metaDisplay">Current metadata: None πŸ“</p>

<script>
  const video = document.getElementById("myVideo");
  const metaTrack = document.getElementById("metaTrack").track;
  const metaDisplay = document.getElementById("metaDisplay");

  metaTrack.addEventListener("cuechange", () => {
    const activeCues = metaTrack.activeCues;
    if (activeCues.length > 0) {
      metaDisplay.textContent = `Current metadata: ${activeCues[0].text} πŸ“`;
    } else {
      metaDisplay.textContent = "Current metadata: None πŸ“";
    }
  });
</script>

In this example, the metadata track fires custom events, and the display updates accordingly.

When to Use the cuechange Event

The cuechange event is particularly useful in scenarios where:

  • You need to update subtitles dynamically.
  • You want to display descriptions for accessibility.
  • You handle custom metadata events to enhance user experience.

Comparing cuechange with Other Media Events

To understand the cuechange event better, let’s compare it with other common media events.

EventDescriptionExample Usage
cuechangeFired when a cue in a text track becomes active or inactiveUpdate UI with current subtitles or metadata
timeupdateFired when the playback position changesUpdate a progress bar
playFired when the media begins to playLog a message when playback starts
pauseFired when the media is pausedLog a message when playback pauses
endedFired when playback reaches the end of the mediaShow a replay button

Code Examples of Different Events

Here’s how you can use some of these events in your code:

HTML
<video id="myVideo" controls>
  <source src="movie.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>

<p id="status">Status: Not started ⏸️</p>

<script>
  const video = document.getElementById("myVideo");
  const statusDisplay = document.getElementById("status");

  video.addEventListener("play", () => {
    statusDisplay.textContent = "Status: Video is playing ▢️";
  });

  video.addEventListener("pause", () => {
    statusDisplay.textContent = "Status: Video is paused ⏸️";
  });

  video.addEventListener("ended", () => {
    statusDisplay.textContent = "Status: Video ended πŸŽ‰";
  });

  video.addEventListener("timeupdate", () => {
    statusDisplay.textContent = `Current time: ${video.currentTime} seconds ⏱️`;
  });
</script>

Conclusion

The cuechange event in JavaScript is a powerful tool for managing changes in text tracks within media elements. By understanding and using this event, you can create more dynamic and interactive web applications. Whether you are working with subtitles, descriptions, or custom metadata, the cuechange event can enhance the functionality and user experience of your projects.

Summary

  • What: The cuechange event fires when a cue in a text track becomes active or inactive.
  • Why: It helps in updating UI elements and handling cue-based actions.
  • Where: Use it with HTML media elements like <audio> and <video> that have text tracks.
  • How: By adding an event listener for cuechange and updating the necessary elements.
  • When: Use it whenever you need to respond to changes in text tracks, especially with dynamic media content.

Feel free to use the examples provided and modify them to suit your needs. Happy coding! πŸŽ‰

What are JavaScript Browser Events?

JavaScript browser events are key to creating interactive web applications. These events are actions or occurrences detected by the browser, such as user interactions, document changes, or window modifications. By responding to events like clicks, key presses, and form submissions, developers can enhance user experience and functionality.

This comprehensive list of JavaScript browser events is a valuable reference for developers. It covers a wide range of events, from mouse and keyboard actions to document and window changes. Understanding and handling these events is essential for building responsive and engaging web applications, ensuring a seamless and intuitive user experience.

See List of all JavaScript Browser Events – Cheat Sheet

  • Document events:
    • ended
    • error
    • loadeddata
    • loadedmetadata
    • loadstart
    • pause
    • play
    • playing
    • progress
    • ratechange
    • seeked
    • seeking
    • stalled
    • suspend
    • timeupdate
    • volumechange
    • waiting
    • emptied
    • durationchange
    • cuechange
    • change
    • canplaythrough
    • canplay
    • abort
    • DOMContentLoaded
  • Window events:
    • afterprint
    • beforeprint
    • beforeunload
    • error
    • hashchange
    • load
    • message
    • offline
    • online
    • pagehide
    • pageshow
    • popstate
    • resize
    • scroll
    • storage
    • unload
  • Form events:
    • submit
    • select
    • reset
    • invalid
    • input
    • focus
    • change
    • blur
  • Keyboard events:
    • keyup
    • keypress
    • keydown
  • Mouse events:
    • wheel
    • mouseup
    • mouseover
    • mouseout
    • mousemove
    • mouseleave
    • mouseenter
    • mousedown
    • dblclick
    • contextmenu
    • click

Leave a Reply