1

I have 2 fullscreen background videos that I want to change dynamically based on the time of day (ex. looping day video from 6 a.m. to 7 p.m. vs. looping night video from 7 p.m. to 6 a.m.). Currently, I'm commenting out the video that I don't want to play. Any advice on how to do this with JS would be much appreciated. (Videos are located in a folder called "video").

HTML:

<div class="video_contain">
            <!-- video day -->
            <video autoplay loop id="video-background" muted plays-inline>
                <source src="video/catbeats-loop-day-720p.m4v" poster="img/catbeats-day.gif" type="video/mp4">
            </video>

            <!-- video night -->
            <!-- <video autoplay loop id="video-background" muted plays-inline>
                <source src="video/catbeats-loop-night-720p.m4v" poster="img/catbeats-night.gif" type="video/mp4">
            </video> -->
</div>

CSS:

.video_contain {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -100;
}

#video-background {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: auto;
    min-width: 100%; 
    min-height: 100%;
    width: auto; 
    height: auto;
}
jorscobry
  • 113
  • 7

1 Answers1

1

try to create the src element with js depeding on the hour of the day and then append it to your video element, answer is inspired from this post.

changing source on html5 video tag

feel free to correct and improve this code.

var currentTime = new Date().getHours();
var video = document.getElementById('video-background');
var source = document.createElement('source');

if (6 <= currentTime && currentTime < 7) {
source.setAttribute('src', 'https://storage.googleapis.com/coverr-main/mp4/The-Slow-Dock.mp4');
video.appendChild(source);
video.play();
}
else {
    source.setAttribute('src', 'https://storage.googleapis.com/coverr-main/mp4/Night-Traffic.mp4');
video.appendChild(source);
video.play();
}
.video_contain {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -100;
}

#video-background {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: auto;
    min-width: 100%; 
    min-height: 100%;
    width: auto; 
    height: auto;
}
<div class="video_contain">
            <video autoplay loop id="video-background" muted plays-inline></video>
</div>
Imad El Haj
  • 101
  • 5
  • This worked. The only thing I changed was if (6 <= currentTime && currentTime < 7) to if (6 <= currentTime && currentTime < 19) so that it works on a 24hr clock. Thanks! – jorscobry Nov 02 '18 at 23:07