htmlhtml5-videogetelementbyidscript-tag

Change video source script doesn't work, code changes but view does not


I am trying to build a dynamic webpage and having a issue about changing the playing video. I want to put a button and when user clicks on it, video should change. I am trying to use changing video source by a script. When i inspect, it changes the value of src href but it does not effect the view. Still old video plays. What should i change to make it work?

Here is my code:

<div id="source_change" class="source">CHANGE SOURCE</div>

<video style="position: relative; left: -47px; border-radius: 45px;" autoplay="autoplay" loop="loop" muted="" width="642" height="324"><source id="source_video" src="firstvideo.mp4" type="video/mp4" />
</video>

<script>
  document.getElementById('source_change').addEventListener('click', function() {
  document.getElementById('source_video').src = 'secondvideo.mp4';
  });
</script>

Solution

  • You need to set the ID on the <video> tag itself.
    You might also need to do a load() afterwards to init the new source.

    Try having a code setup like this:

    <div id="source_change" class="source">CHANGE SOURCE</div>
    
    <video  id="source_video" 
            style="position: relative; left: -47px; border-radius: 45px;" 
            autoplay="autoplay" loop="loop" muted="" width="642" height="324">
            
    <source src="firstvideo.mp4" type="video/mp4" />
    </video>
    
    <script>
    
    let myBtn = document.getElementById('source_change')
    let myVid = document.getElementById('source_video');
    
    myBtn.addEventListener('click', on_BtnClick );
      
    function on_BtnClick ()
    {
        myVid.src = 'secondvideo.mp4';
        myVid.load();
    }
    
    </script>