'Random background video on page load with html/js
Is worked my way through all responses but i just can't get my head around how to make this work. I want to have a selection of 4 background videos which random on load. So far, this is what i got.
const possibleVideos = ["/_1/video/bgvid3.mp4", "/_1/video/bgvid2.mp4"];
const randomVideo = possibleVideos[Math.floor(Math.random() * possibleVideos.length)];
document.querySelector('video.background-video').src = randomVideo;
<video id="background-video" disablepictureinpicture controlslist="nodownload" autoplay loop muted poster="">
<source src="/_1/video/bgvid3.mp4" type="video/mp4">
</video>
I understand how the parts work but i dont understand how to connect them.
Solution 1:[1]
If your file paths are correct then try something like this (study the code as to why it works):
<!DOCTYPE html>
<html>
<body>
<video id="background-video" controls muted>
<source src="none.mp4" type="video/mp4">
</video>
</body>
<script>
const possibleVideos = ["/_1/video/bgvid3.mp4", "/_1/video/bgvid2.mp4"];
//# get a randoom number
//# note: Array length is 2 but Array item1 starts at [0], item2 is at [1]..
const randomNum = Math.floor( Math.random() * (possibleVideos.length-1) )
const randomVideo = possibleVideos[ randomNum ];
//# access the required video tag
const myVid = document.getElementById('background-video');
//# load and play the new "src" file
myVid.src = randomVideo;
myVid.load();
myVid.play();
</script>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VC.One |
