TrackEvent

TheTrackEventinterface of theHTML DOM APIis used for events which represent changes to a set of available tracks on an HTML media element; these events areaddtrackandremovetrack.

It's important not to confuseTrackEventwith theRTCTrackEventinterface, which is used for tracks which are part of anRTCPeerConnection.

Events based onTrackEventare always sent to one of the media track list types:

Event TrackEvent

Constructor

TrackEvent()

Creates and initializes a newTrackEventobject with the event type specified, as well as optional additional properties.

Instance properties

TrackEventis based onEvent,so properties ofEventare also available onTrackEventobjects.

trackRead only

The DOM track object the event is in reference to. If notnull,this is always an object of one of the media track types:AudioTrack,VideoTrack,orTextTrack).

Instance methods

TrackEventhas no methods of its own; however, it is based onEvent,so it provides the methods available onEventobjects.

Example

This example sets up a function,handleTrackEvent(),which is called for anyaddtrackorremovetrackevent on the first<video>element found in the document.

js
const videoElem = document.querySelector( "video" );

videoElem.videoTracks.addEventListener( "addtrack", handleTrackEvent, false);
videoElem.videoTracks.addEventListener( "removetrack", handleTrackEvent, false);
videoElem.audioTracks.addEventListener( "addtrack", handleTrackEvent, false);
videoElem.audioTracks.addEventListener( "removetrack", handleTrackEvent, false);
videoElem.textTracks.addEventListener( "addtrack", handleTrackEvent, false);
videoElem.textTracks.addEventListener( "removetrack", handleTrackEvent, false);

function handleTrackEvent(event) {
let trackKind;

if (event.target instanceof VideoTrackList) {
trackKind = "video";
} else if (event.target instanceof AudioTrackList) {
trackKind = "audio";
} else if (event.target instanceof TextTrackList) {
trackKind = "text";
} else {
trackKind = "unknown";
}

switch (event.type) {
case "addtrack":
console.log(`Added a ${trackKind} track`);
break;
case "removetrack":
console.log(`Removed a ${trackKind} track`);
break;
}
}

The event handler uses the JavaScriptinstanceofoperator to determine which type of track the event occurred on, then outputs to console a message indicating what kind of track it is and whether it's being added to or removed from the element.

Specifications

Specification
HTML Standard
#the-trackevent-interface

Browser compatibility

BCD tables only load in the browser