I am running the following code which changes the source of an html5 video as soon as the initial source ends. After the first video finishes, it runs the second, then third and eventually starts again from the beginning, resulting in an endless cycle.
var myvid = document.getElementById('myvideo');
var myvids = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = 0;
myvid.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % myvids.length;
// update the video source and play
myvid.src = myvids[activeVideo];
myvid.play();
});
<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" autoplay muted playsinline style="background:black">
</video>
Now my question is: How can I randomize which of the videos in the javascript code comes first? I would like it to randomly choose one from the list, whenever the code is executed the first time. After choosing a random starting point, it should go through the list in the normal order. It shouldn't make every video random, only the starting point.
You can try this :
function getRandomIndex(max) {
/* The function will return a random number between 0 and max - 1 */
return Math.floor(Math.random() * Math.floor(max));
}
function randomlyChooseVideo() {
activeVideo = getRandomIndex(myvids.length);
// update the video source and play
myvid.src = myvids[activeVideo];
myvid.play();
}
var myvid = document.getElementById('myvideo');
var myvids = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
/* The initial active video will radomly be choosen between 0 and videoArray length - 1 */
var activeVideo = getRandomIndex(myvids.length);
window.onload = function(e) {
randomlyChooseVideo()
}
myvid.addEventListener('ended', function(e) {
randomlyChooseVideo()
});
<video src="" id="myvideo" width="320" height="240" autoplay muted playsinline style="background:black">
</video>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With