Search code examples
javascripthtml5-videoplaylist

Play selected video


    <script type="text/javascript">
function playVideo(sourceId, targetId) {
   if (typeof(sourceId)=='string') {sourceId=document.getElementById(sourceId);}
   if (typeof(targetId)=='string') {targetId=document.getElementById(targetId);}
   targetId.innerHTML=sourceId.innerHTML;
   return false;

   }
    </script>
<video id="6" width="320" height="240" controls="controls"></video>

<video id="1" style="display: none;"width="320" height="240" controls="controls">
  <source src="movie1.mp4" type="video/mp4" />
  <source src="movie1.ogg" type="video/ogg" /> 
  <source src="movie1.webm" type="video/webm" />
Your browser does not support the video tag.
</video>
<video id="2" style="display: none;" width="320" height="240" controls="controls">
  <source src="movie2.mp4" type="video/mp4" />
  <source src="movie2.ogg" type="video/ogg" /> 
  <source src="movie2.webm" type="video/webm" />
Your browser does not support the video tag.
</video>


<a href="#" onclick='return playVideo("1","6")'>Play Video 1</a>
<a href="#" onclick='return playVideo("2","6")'>Play Video 2</a>

When selecting "Play Video 2" while Video 1 is playing video 2 will not work, how can i resolve this? Is there additional script I have to add so that the second video will override the first?


Solution

  • <script type="text/javascript">
        function playVideo(sourceId, targetId) {
            if (typeof(sourceId)=='string') {sourceId=document.getElementById(sourceId);}
            if (typeof(targetId)=='string') {targetId=document.getElementById(targetId);}
            targetId.innerHTML=sourceId.innerHTML;
            return false;
        }
    </script>
    
    <div id="6"></div>
    
    <div id="1" style="display: none">
        <video width="320" height="240" controls="controls">
            <source src="movie1.mp4" type="video/mp4" />
            Your browser does not support the video tag.
        </video>
    </div>
    
    <div id="2" style="display: none">
        <video width="320" height="240" controls="controls">
            <source src="movie2.avi" type="video/avi" />
            Your browser does not support the video tag.
        </video>
    </div>
    
    <a href="#" onclick='return playVideo("1","6")'>Play Video 1</a>
    <a href="#" onclick='return playVideo("2","6")'>Play Video 2</a>
    

    What I did: I placed the two video elements within invisible divs. Those divs have ids (1 & 2) and the content of those divs (your video elements) are loaded into a third (visible) div with id 6.