Turn closed captions off for multiple videos with global button

179 views Asked by At

I have a page containing multiple HTML5 videos with different captions (webvtt). The video controls are hidden. I have a button «add subtitles» with the ID #check. If the user checks this button, ALL videos should display the captions, and if unchecked, the captions should be hidden. What I have so far:

Hide captions by default:

var video = document.querySelector('.video');
var tracks = video.textTracks;
var track = tracks[0];

$(document).ready(function() {
  track.mode = 'hidden';
});

If button is checked/unchecked, show/hide captions:

$(function() {
  $('#check').click(function() {
    if($(this).is(':checked')) {
      track.mode = 'showing';
    }  else {
      track.mode = 'hidden';
    }
  });
});

This works perfectly BUT only for the first video (since tracks[0] only delivers the value of the first track). Is there anything I can do to solve this issue or am I on a completely wrong path?

1

There are 1 answers

5
Lajos Arpad On BEST ANSWER

You just need to iterate tracks, like this:

$(function() {
  $('#check').click(function() {
    var isChecked = $(this).is(':checked');
    for (var index = 0; index < tracks.length; index++) {
        tracks[index].mode = (isChecked ? 'showing' : 'hidden');
    }
  });
});

EDIT

The reason that only the first is affected is that you are selecting the very first video. Change your first code to:

var video = document.querySelectorAll('.video'); //querySelector selects the first match only
var videoTrackSets = [];
for (var videoIndex = 0; videoIndex < video.length; videoIndex++) {
    videoTrackSets.push(video[videoIndex].textTracks);
}

$(document).ready(function() {
    for (var setIndex = 0; setIndex < videoTrackSets; setIndex++)
        for (var trackIndex = 0; trackIndex < videoTrackSets[setIndex].length; trackIndex++)
            videoTrackSets[setIndex][trackIndex].mode = 'hidden';
});

and change the second code to

$(function() {
  $('#check').click(function() {
    var isChecked = $(this).is(':checked');
    for (var setIndex = 0; setIndex < videoTrackSets.length; setIndex++)
        for (var trackIndex = 0; trackIndex < videoTrackSets[setIndex].length; trackIndex++)
            videoTrackSets[setIndex][trackIndex].mode = (isChecked ? 'showing' : 'hidden');
  });
});