Home  >  Article  >  Web Front-end  >  How to Dynamically Change the Source of an HTML5 Video Tag?

How to Dynamically Change the Source of an HTML5 Video Tag?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 14:20:02866browse

How to Dynamically Change the Source of an HTML5 Video Tag?

Changing the Source of an HTML5 Video Tag: A Comprehensive Solution

Creating a universal video player requires addressing the issue of dynamically changing the source of the video. This allows users to switch between videos in a playlist. While previous approaches using multiple tags have faced limitations, this article presents a reliable method using a single attribute.

Identifying the File Type Using canPlayType():

To determine the appropriate file type for the video, we can utilize the canPlayType() function. This function returns a string indicating the browser's level of support for a given media type. For example:

var canPlayMP4 = video.canPlayType('video/mp4');
var canPlayWebM = video.canPlayType('video/webm');

Based on the results of canPlayType(), we can dynamically set the src attribute of the

Implementation Using Vanilla JavaScript:

Here's a code snippet demonstrating how to change the source of the video using vanilla JavaScript:

var video = document.getElementById('video');

// Create a new source element
var source = document.createElement('source');

// Set the source attributes dynamically based on browser support
if (canPlayMP4) {
  source.setAttribute('src', 'video.mp4');
  source.setAttribute('type', 'video/mp4');
} else if (canPlayWebM) {
  source.setAttribute('src', 'video.webm');
  source.setAttribute('type', 'video/webm');
}

// Append the source to the video element
video.appendChild(source);

// Play the video
video.play();

This approach allows for dynamic source switching without the drawbacks of using multiple tags. It also ensures that the video will play in the most suitable format supported by the browser.

The above is the detailed content of How to Dynamically Change the Source of an HTML5 Video Tag?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn