I'm currently working on a one page website project using the Bulma framework, and my site currently has one background video that plays as the user scrolls through the site. However, I'd like to possibly add some more videos and have a different one play randomly on refresh. I have found JS code that works, but it pulls videos from the internet, whereas mine are saved in a folder; when I put the filenames in, it doesn't work.
Here's the JS code that worked for me at first
var videoStorage = [
'//media.w3.org/2010/05/sintel/trailer',
'//techslides.com/demos/sample-videos/small',
'//fat.gfycat.com/DazzlingCompleteAnkole',
'//zippy.gfycat.com/HeavyPlumpIvorybilledwoodpecker'
],
video = document.querySelector('video'),
// choose one random url from our storage as the active video
activeVideoUrl = videoStorage[Math.round(Math.random() * (videoStorage.length - 1))];
// check which file extension your browser can play and set the video source accordingly
if(video.canPlayType('video/webm')) {
video.setAttribute('src', activeVideoUrl + '.webm');
} else if(video.canPlayType('video/mp4')) {
video.setAttribute('src', activeVideoUrl + '.mp4');
}
Here's the HTML I have for the one video so far
<section id="home" class="hero is-fullheight-with-navbar video">
<div class="hero-video">
<video id="bgvid" playsinline autoplay muted loop>
<source src="images/i_know_what_i_like.mp4" type="video/mp4">
</video>
</div>
Since that JS code did do its job, is there a way to make it work using the files I have saved in a folder?
Read the notes. I expect your url was not loading because you were providing the extension. E.g: images/i_know_what_i_like.mp4
would become images/i_know_what_i_like.mp4.mp4
or images/i_know_what_i_like.mp4.webp
, which probably aren't existing url's.
One solution would be to not add the extension with JS.
// NOTE: make sure these are valid working urls.
var videoStorage = [
'images/i_know_what_i_like.mp4'
];
let video = document.querySelector('video');
// choose one random url from our storage as the active video
// NOTE: you don't want to use Math.round() here, use Math.floor() instead
let activeVideoUrl = videoStorage[Math.floor(Math.random() * videoStorage.length];
// NOTE: you are providing the extension so no need to add it in JS
video.setAttribute('src', activeVideoUrl);