samedi 19 octobre 2019

Play a random video on button click

I'm having some trouble with something and I'm hoping someone can help me. I should start by saying I'm not good with JS and I'm still trying to learn it.

I have 10 mp4s and I need to play one at random on a button click. I'm having trouble making it happen and I've searched around for a solution but to no avail.

Here's what I have so far:

HTML

<div class="videoHolder">
    <video id="video" autoplay muted>
    Your browser does not support the video tag.
    </video>
</div>
<button type="button" name="button">Push to Play</button> 

JS

var videos = [
    "mp4s/video1.mp4",
    "mp4s/video2.mp4",
    "mp4s/video3.mp4",
    "mp4s/video4.mp4",
    "mp4s/video5.mp4",
    "mp4s/video6.mp4",
    "mp4s/video7.mp4",
    "mp4s/video8.mp4",
    "mp4s/video9.mp4",
    "mp4s/video10.mp4",
];

var videoId = 0;
var elemVideo = document.getElementById('video');
var elemSource = document.createElement('source');
elemVideo.appendChild(elemSource);

elemVideo.addEventListener('ended', play_next, false);


function play_next() {
    if (videoId == 10) {
        elemVideo.stop();
    } else {
        video.pause();
        elemSource.setAttribute('src', videos[videoId]);
        videoId++;
        elemVideo.load();
        elemVideo.play();
    }
}
play_next();

This unfortunately doesn't do what I need. This code will play all 10 videos one after the other on page load, then stop. I need it to only play one of the random 10 videos when someone pushes the "Push to Play" button. And I need it to keep going after 10.

Any help would be really appreciated. Like I said I'm not good with JS at all and I was able to find this code from browsing around and modifying it a bit.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire