nourza
nourza

Reputation: 2321

Playing the next video when the first one end with video tag as a playlist

Hi I am not that good with javascript

I have videos and I want when the first video end to play the next video and so. Here is what I tried.

<div id="myvideo" style="width: 100%; height: 400px; overflow: hidden;">
      <%= video_tag "men-kicking-punching-fighting-during-combat-sport-karate-simulation_b8ltmb7kqx_1080__D.mp4", muted: 'muted',autoplay: :true ,style: 'display: block; height: 100%; width: 100%; object-fit: cover;', class: "active"%>
      <%= video_tag "young-woman-dancing-on-the-stairs_hsua5f2_1080__D.mp4", muted: 'muted',autoplay: :true,style: 'display: block; height: 100%; width: 100%; object-fit: cover;'%>
      <%= video_tag "videoblocks-happy-arabian-uae-sheikh-man-walks-in-middle-of-white-desert-and-enjoys-life-on-hot-summer-day_rbtvafcvw_1080__D.mp4", muted: 'muted',autoplay: :true,style: 'display: block; height: 100%; width: 100%; object-fit: cover;' %>
    </div>

in java script

    <script type="text/javascript">
var myvid = document.getElementById('myvideo');

myvid.addEventListener('ended', function(e) {
  // get the active source and the next video source.
  // I set it so if there's no next, it loops to the first one
  var activevideo = document.querySelector("#myvideo video.active");
  var nextvideo = document.querySelector("#myvideo video.active + video_tag") || document.querySelector("#myvideo video:first-child");
  
  // deactivate current source, and activate next one
  activevideo.className = "";
  nextvideo.className = "active";
  
  // update the video source and play
  myvid.srcObject = nextvideo.srcObject;
  myvid.play();
});</script>

Upvotes: 1

Views: 960

Answers (1)

Fernando rivas
Fernando rivas

Reputation: 84

To autoplay your videos 1 by1 when one had finished with 3 videos remove the autoplay in order for your JS to work properly :

<script type="text/javascript">

const videos = document.getElementsByTagName('video') 
videos[0].play()

videos[0].addEventListener('ended',function(e){

videos[1].play()

videos[1].addEventListener('ended',function(e){

videos[2].play()

videos[2].addEventListener('ended',function(e){

videos[0].play()

})

})

})

</script>

Upvotes: 2

Related Questions