Sling Academy
Home/JavaScript/Display Multi-Language Subtitles Using JavaScript and WebVTT

Display Multi-Language Subtitles Using JavaScript and WebVTT

Last updated: December 14, 2024

In today’s globalized world, making online video content accessible to a wider audience is crucial. One effective way to achieve this is by adding subtitles in multiple languages. Using JavaScript and WebVTT (Web Video Text Tracks), we can display multilingual subtitles easily.

Understanding WebVTT

WebVTT is a widely supported subtitle format for web videos. It is simple to use and easily integrates with HTML5 video elements. Each WebVTT file consists of text cues paired with time ranges, allowing precise synchronization with the video. Below is a basic structure of a WebVTT file:


WEBVTT

00:00:01.000 --> 00:00:04.000
Hello, welcome to our video!

00:00:05.000 --> 00:00:07.000
Thank you for watching.

Setting Up the HTML5 Video

The HTML <video> element is key to displaying videos with subtitles. Multiple subtitle tracks can be embedded in this element, one for each language. Here's how you can set up a language-specific subtitle track:


<video id="myVideo" controls>
  <source src="video.mp4" type="video/mp4">
  <track label="English" kind="subtitles" srclang="en" src="subtitles_en.vtt" default>
  <track label="Spanish" kind="subtitles" srclang="es" src="subtitles_es.vtt">
  <track label="French" kind="subtitles" srclang="fr" src="subtitles_fr.vtt">
Your browser does not support the video tag.
</video>

Each <track> element includes a label for user selection, a kind that is typically set to "subtitles", a srclang to indicate language, and a src attribute to point to the WebVTT file path.

Displaying Subtitles with JavaScript

To dynamically toggle subtitles, JavaScript can help manage the video's text track list. Let's walk through a simple JavaScript functionality to allow users to switch between subtitles:


window.addEventListener('DOMContentLoaded', (event) => {
    const video = document.getElementById('myVideo');
    const tracks = video.textTracks;

    // Initially hide all tracks
    for (let i = 0; i < tracks.length; i++) {
        tracks[i].mode = 'hidden';
    }

    function setTrack(language) {
        for (let i = 0; i < tracks.length; i++) {
            if (tracks[i].language === language) {
                tracks[i].mode = 'showing';
            } else {
                tracks[i].mode = 'hidden';
            }
        }
    }

    // Example of setting English subtitles
    document.getElementById('subtitle-en').addEventListener('click', () => {
        setTrack('en');
    });

    // Add more event listeners for other languages
    document.getElementById('subtitle-es').addEventListener('click', () => {
        setTrack('es');
    });

    document.getElementById('subtitle-fr').addEventListener('click', () => {
        setTrack('fr');
    });
});

This code snippet sets up click event listeners on buttons that, when triggered, change the subtitle language by manipulating the text track modes.

Add Language Selection UI

For a user-friendly UI, create a language selection interface. Here's a simple dropdown example:


<select id="languageSelector">
  <option value="en">English</option>
  <option value="es">Spanish</option>
  <option value="fr">French</option>
</select>

Listen for changes in the dropdown and switch the subtitles:


document.getElementById('languageSelector').addEventListener('change', function() {
    setTrack(this.value);
});

Conclusion

Displaying multilingual subtitles using JavaScript and WebVTT enhances accessibility and user experience. By following the steps outlined above, you can seamlessly provide multilingual support in your video content. This not only increases audience reach but also enhances the engagement and understanding of the material presented.

Next Article: Integrate Accessibility Features via the WebVTT API in JavaScript

Previous Article: Synchronize Text Tracks with Media via JavaScript WebVTT

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration