user18194401
user18194401

Reputation: 13

Target video source in HTML with JavaScript

My video is not playing after editing the source via JavaScript, can you help me with that?

HTML : <video class="background-video" controls muted loop autoplay>
       <source id="vid_tag" type="video/mp4"></video>

JS : document.querySelector('#vid_tag').src = "_1/video/bvid_1.mp4"

Upvotes: 1

Views: 1141

Answers (2)

Kaiido
Kaiido

Reputation: 136678

When you set the src attribute of a <source> element you need to call the <video>'s .load() method for it to fetch the new value:

document.querySelector("button").addEventListener("click", (evt) => {
  const url = "https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm";
  document.querySelector("source").src = url;
  document.querySelector("video").load(); // required
}, { once: true });
<video controls muted loop autoplay>
  <source id="vid_tag" type="video/webm">
</video>
<button>set source</button>

However, you'd be better not using the <source> at all anymore if you do set its src dynamically.
If you were using it for its ability to fallback when facing unsupported formats, then use the <video>.canPlayType() method instead:

document.querySelector("button").addEventListener("click", (evt) => {
  const url = "https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm";
  const video = document.querySelector("video");
  if (video.canPlayType("video/webm")) {
    video.src = url;
  }
  else {
    // to-do: load an other source
    console.warn("format is not supported");
  }
}, { once: true });
<video controls muted loop autoplay></video>
<button>set source</button>

Upvotes: 0

DevWolf31
DevWolf31

Reputation: 86

It could be an error with the path, maybe you wrote it wrong and the browser does not find it.

Possible Solution:

(1) Fix HTML:
The ID should be written in the <video> tag's setup (not put in <source> tag)

<video id="vid_tag" class="background-video" controls muted loop autoplay>
<source src="nothing.mp4" type="video/mp4">
</video>

(2) Fix JS:

Replace document.querySelector('#vid_tag') with something more direct like document.getElementById("vid_tag") where you access by the specific ID of the Element you want.

document.getElementById("vid_tag").src = "_1/video/bvid_1.mp4"; //# set new src
document.getElementById("vid_tag").load(); //# decode (process) the new file

Upvotes: 1

Related Questions