1

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"
1
  • So it appears to work if i go to another page on the web and return to my liveserver view of the homepage... this is even more confusing Commented Apr 7, 2022 at 23:58

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't put comments in an Answer box. I've updated with a possible solution so you get enough rep to allow comments.
this did it! additionally i had a mistake in the <script> tag by calling for type=“text/javascript“ which made it break. im so happy, thanks alot!
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.