March March - 1 month ago 8
Javascript Question

Can I use javascript to dynamically change a video's source?

How can I change a video's source using JS?

<video id="myVideoTag" width="670" height="377" autoplay="true" controls="controls">
<source src="http://www.test.com/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>

Answer

Sure, you can just set the src attribute on the source element:

document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4"

Or using jQuery instead of standard DOM methods:

$("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4"​​​​)​
Comments