crarls crarls - 7 months ago 73
Javascript Question

Randomized HTML5 background video on page load/refresh

I've implemented an HTML5 video as a full screen background video. Each time someone opens the page or refreshes it, I'd like to have the background video randomly change to another one (I'll have about 3 or 4 videos that could be chosen.) Until the page is refreshed or reopened just that one video would play, though. It wouldn't loop through the 3 or 4 videos if that makes sense.

This question was flagged as a duplicate for another, which gave me part of the answer.

var videoList = ["video1", "video2", "video3", "video4", "video5"];
videoList.sort(function (a, b) {
return Math.random() > 0.5 ? -1 : 1;

My question now is, how do I 'tie' these video files to the source of the html video?

<video autoplay poster="" id="bgvid" loop>
<source src="?" type="video/webm">
<source src="?" type="video/mp4">


Since the edit of the question, it isn't a duplicate of the other that I mentioned in the comments. So here's an attempt!

This should hopefully be what you want (working fiddle here:

HTML (with text overlaying the background video, maximize the right panel to see the video playing behind the text):

<div id="videoplayer" width="600" height="800"></div>



var videoList = ["", ""];
videoList.sort(function(a, b) {return 0.5 - Math.random()});

$("#videoplayer").html("<video id='rawvideo' autoplay poster='' id='bgvid' loop><source src='" + videoList[0] + "' type='video/mp4'></video>");


#videoplayer {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;

#rawvideo {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;