TrackEvent
TheTrackEvent
interface of theHTML DOM APIis used for events which represent changes to a set of available tracks on an HTML media element; these events areaddtrack
andremovetrack
.
It's important not to confuseTrackEvent
with theRTCTrackEvent
interface, which is used for tracks which are part of anRTCPeerConnection
.
Events based onTrackEvent
are always sent to one of the media track list types:
- Events involving video tracks are always sent to the
VideoTrackList
found inHTMLMediaElement.videoTracks
- Events involving audio tracks are always sent to the
AudioTrackList
specified inHTMLMediaElement.audioTracks
- Events affecting text tracks are sent to the
TextTrackList
object indicated byHTMLMediaElement.textTracks
.
Constructor
TrackEvent()
-
Creates and initializes a new
TrackEvent
object with the event type specified, as well as optional additional properties.
Instance properties
TrackEvent
is based onEvent
,so properties ofEvent
are also available onTrackEvent
objects.
track
Read only-
The DOM track object the event is in reference to. If not
null
,this is always an object of one of the media track types:AudioTrack
,VideoTrack
,orTextTrack
).
Instance methods
TrackEvent
has no methods of its own; however, it is based onEvent
,so it provides the methods available onEvent
objects.
Example
This example sets up a function,handleTrackEvent()
,which is called for anyaddtrack
orremovetrack
event on the first<video>
element found in the document.
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 JavaScriptinstanceof
operator 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