Scenario 2: Get and switch between multiple text tracks

Back to scenarios menu

Description

This example builds on the first example by using JavaScript and properties on the video object to get and display the label of each text track below the video player. When the labels are first created, the mode for each associated track is checked. If the mode value = SHOWING, then the label has angle brackets added.

The labels are created as <div> elements and have a click event that's attached to enable the language to change when the text is clicked. When a label is clicked, the mode value of the selected track is updated to SHOWING, and the others are set to disabled. The label in the list of languages is updated with angle brackets to reflect the currently active track.

Currently the testTrackList object doesn't support a change event like the audioTrackList does. This makes it difficult to keep the video player controls and scripted elements that change the track in sync. If you want full control of the tracks, remove the controls attribute on the video player, and write controls to play the video in script.

For more information on scripting the video control, see Add audio and video to your webpage.

Code

//  When the DOM is loaded, create an event to displays the labels of the text tracks once
//  all the media is loaded
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("video1").addEventListener("loadeddata", function () {
        getTracks();
    }, false);    
}, false);

function getTracks() {
    var allTracks = document.getElementById("video1").textTracks; // get list of tracks   
    document.getElementById("display").innerHTML = ""; // clear text       
     for (var i = 0; i < allTracks.length; i++) {
        //  append track label with a click event 
        var temp = document.createElement("div");
        //  create labels that highlight the active track
        if (allTracks[i].mode == 2)
        {
           temp.innerText = "> " + allTracks[i].label + " <";
        }else{
           temp.innerText = allTracks[i].label;
        }
        temp.setAttribute("onclick", "changeTrack(" + i + ")");
        temp.setAttribute("role", "button");
        temp.setAttribute("id", i);
        document.getElementById("display").appendChild(temp);
    }
}

function changeTrack(index) {
    var allTracks = document.getElementById("video1").textTracks; // get list of tracks
    for (var i = 0; i < allTracks.length; i++) {
        if (i == index) {
            allTracks[i].mode = 2; // show this track
            document.getElementById(i).innerText = "> " + allTracks[i].label + " <";
        } else {
            allTracks[i].mode = 0; // hide all other tracks
            document.getElementById(i).innerText = allTracks[i].label;
        }
    }
} 

Result