Home > Web Front-end > JS Tutorial > How to Dynamically Change Video Sources in HTML5 without Browser Compatibility Issues?

How to Dynamically Change Video Sources in HTML5 without Browser Compatibility Issues?

Susan Sarandon
Release: 2024-11-23 07:34:14
Original
1057 people have browsed it

How to Dynamically Change Video Sources in HTML5 without Browser Compatibility Issues?

Dynamically Changing Video Sources in HTML5

Problem Description

When attempting to dynamically change video sources in an HTML5

Solution

To overcome this problem, consider the following approach that uses the canPlayType() function:

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

function changeSource(newUrl) {
  // Remove existing `<source>` tags
  while (video.children.length > 0) {
    video.removeChild(video.children[0]);
  }

  // Create a new `<source>` tag with the new URL
  const source = document.createElement('source');
  source.src = newUrl;

  // Determine the appropriate MIME type using `canPlayType()`
  const mimeType = video.canPlayType('video/mp4') ? 'video/mp4' : 'video/webm';
  source.type = mimeType;

  // Append the new `<source>` tag to the video element
  video.appendChild(source);

  // Reload the video
  video.load();
  video.play();
}
Copy after login

Explanation

This solution involves removing existing tags, creating a new one with the desired URL, and determining the appropriate MIME type using canPlayType(). The new source is then appended to the video element, and the video is reloaded. This approach works effectively in both Chrome and Firefox.

The above is the detailed content of How to Dynamically Change Video Sources in HTML5 without Browser Compatibility Issues?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template