Use Javascript to randomize background video on page load - javascript

I'd like to randomly load a video on page load. I have three videos stored locally that I'd like to alternate between but can't seem to get any others except the first to play. I'm very new to Javascript and quite lost on what needs to be fixed...thanks for any help!
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
var videoStorage = [
'/vid/background-video-1.mp4',
'/vid/background-video-2.mp4',
'/vid/background-video-3.mp4'
],
video = document.querySelector('video'),
activeVideoUrl = videoStorage[Math.round(Math.random() * (videoStorage.length - 1))];
</script>
</head>
<body>
<div class="overlay">
<video autoplay muted loop id="background-video">
<source src="/vid/background-video-1.mp4" type="video/mp4">
<source src="/vid/background-video-2.mp4" type="video/mp4">
<source src="/vid/background-video-3.mp4" type="video/mp4">
</video></div>

Your activeVideoUrl is only set once on page load. Try using setInterval to update the value of activeVideoUrl.

You have to set src from this activeVideoUrl random selected url, you can set video type and play,
You can try this,
var videoStorage = [
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4'
],
video = document.querySelector('#background-video');
// DEFAULT PLAY ON PAGE LOAD
randomPlay();
// RANDOM PLAY FUNCTION
function randomPlay(){
let activeVideoUrl = videoStorage[
Math.round(Math.random() * (videoStorage.length - 1))
];
video.type = "video/mp4";
video.src = activeVideoUrl;
video.play();
}
<button onClick="randomPlay()">Random Play</button>
<div class="overlay">
<video autoplay muted loop id="background-video" height="150px"></video>
</div>

Needed to add document.addEventListener("DOMContentLoaded", function ()
document.addEventListener("DOMContentLoaded", function () {
var videoStorage = [
'/vid/background-video-1.mp4',
'/vid/background-video-2.mp4',
'/vid/background-video-3.mp4'
],
video = document.querySelector('#background-video'),
activeVideoUrl = videoStorage[
Math.floor(Math.random() * (videoStorage.length))
];
video.type = "video/mp4";
video.src = activeVideoUrl;
});
</script>```

Related

Randomize Background Video with Sound, after clicking function

I wrote this code a while back, and it allowed users to click and refresh the page to autoplay a RANDOM background video with sound.
This is the function that they click that loads the function
https://pastebin.com/0XXEHvQQ
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> press me PLAY VIDS :)</a></font></p>
</div>
https://pastebin.com/PD5qdNDM
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> -> press me to fix the site :) <-</a></font></p>
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="js/parallax.js"></script>
<script>
// Pretty simple huh?
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</script>
<script src="js/custom.js"></script>
<script>
let volumeInterval;
function loaded(){
setInterval(loop, 600);
volumeInterval = setInterval(volume, 1);
}
function unload(){
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
console.log("unloaded");
}
function volume() {
try {
document.getElementsByTagName("video")[0].volume = 0.15;
console.log("done!");
clearInterval(volumeInterval);
}
catch (e) {
console.log("waiting..");
}
}
function ok() {
document.write(unescape(
and heres the unescaped code
https://pastebin.com/YJwbG2mC
<!-- VIDEO GRABBB -->
<video preload="auto" autoplay="true" loop="true">
<source id="player" src="5.mp4">
<script>
var video = document.currentScript.parentElement;
video.volume = 0.33;
//document.getElementById('player').currentTime = 20;
</script>
<script>
var video = document.getElementById("player");
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 1000) {
location.reload();
}
});
</script>
<script type="text/javascript">
var video = document.getElementsByTagName('video')[0];
video.onended = function() {
location.reload();
};
</script>
<script>
document.getElementById("player").src = "/" + Math.floor((Math.random()*7)+1) + ".mp4";
</script>
</video>
No matter how I try to adjust the unescaped code, I can't get the MP4 to autoplay after clicking the function.
Here is my live site that I no longer can access: form.wtf
According to the HTML Spec on the Source Element,
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.
Therefore, no matter what you do to the source element, you can't change the video unless the new src is applied directly to the video element.
Replacing the source element also has no effect on the video that plays. The source element's src attribute may changed but the video will keep on playing.
Therefore, you should leave your source's src attribute empty until the JavaScript code sets it or
Leave out the source tag all together and apply the src straight to the video.
Math.floor(Math.random() * 7 + 1); is exactly the same thing as Math.ceil(Math.random() * 7);
document.querySelector('#player > source').src = `/${Math.ceil(Math.random() * 7)}.mp4`;
<video id="player" preload="auto" autoplay loop>
<source src="">
</video>

Javascript: get video duration

I want to get the duration of video by javascript and this code doesn't work
<video id="myVideo">
<source src="">
</video>
<script>
var vid = document.getElementById("myVideo");
alert(vid.duration);
</script>
You need to wait for the file's metadata to load:
var vid = document.getElementById("myVideo");
vid.addEventListener('loadedmetadata', function() {
console.log(vid.duration);
});

How do I make a random video play on pageload?

I'm trying to make a random video player in html/js.
It is supposed to play a different video on pageload and as soon as one video is over, it should play another one.
HTML
<video width="320" height="240" autoplay>
<source src="abcdefg.com/example1.mp4" type="video/mp4">
<source src="abcdefg.com/example2.mp4" type="video/mp4">
</video>
JS
<script>
var videos = [
[{type:'mp4', 'src':'abcdefg.com/example1.mp4'}],
[{type:'mp4', 'src':'abcdefg.com/example2.mp4'}],
];
$(function() {
var number = Math.floor(Math.random()*videos.length);
$(this).find('source').each(function(index){
videoSrc = videos[number][index].src;
$(this).attr('src', videoSrc);
$('video').load();
$('video').play();
});
});
</script>
However, my current code plays the same video every page reload and as soon as it's over, nothing happens.
How do I need to optimize my code so it automatically plays a different video on every pageload + when the previous video is over?
Try this,I have added an event listener to video end property and called the newvideo() function ,so that every time the video finishes a new random video is loaded from array.I could'nt find more video urls ,you can test and let me know if it works for you.
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}]
];
// selecting random item from array,you can make your own
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src)
{
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
//vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(e)
{
newvideo(randomitem[0].src)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video width="320" height="240" autoplay id="myVideo">
</video>

putting different posters at the beginning and ending of html5 video

I can implement a poster at the beginning of a video using poster="beginning.jpg", but how to put a different image at the end of video? example image is like ending.jpg
<video controls width="100%" poster="beginning.jpg" >
<source src="video.mp4" />
</video>
here is jsfiddle
First add an Id to the video.
var video = document.getElementById('video');
var posterURL = 'end.jpg';
// Preload the end poster when the video starts to play
video.addEventListener('play', function() {
var image = new Image();
image.src = posterURL;
});
// Set and display the end poster
video.addEventListener('ended', function() {
video.poster = posterURL;
video.load();
});
Use ended, play events, .load()
<video width="100%" controls poster="/image/src/">
<source src="/video/src/" type="video/mp4" />
</video>
<script>
var video = document.querySelector("video");
video.onplay = function() {
this.setAttribute("poster", "") // remove `poster` image
video.onended = function(e) {
this.setAttribute("poster", "/new/image/src") // set new `poster` image
// call `.load()`
this.load();
}
</script>
jsfiddle https://jsfiddle.net/ey4tfp30/4/

NaN out of get duration in Javascript

I have a problem to get out the duration of an mp4 video file when the html document is ready. My code:
(function ($, root, undefined) {
$(function () {
'use strict';
$(document).ready(function() {
var duration = $("section:first-child() video").get(0).duration;
alert(duration);
});
});
});
The script works in firefox but in chrome it returns an NaN. Im not a javascript professional and i use wordpress HTML5 Blank theme.
Thanks for your help and best regards.
You need to preload the video metadata for you to be able to access them. Then, within the loadedmetadata event, you may access the duration as below.
$(function() {
var $video = $('#video_container').find('video');
$video.on("loadedmetadata", function() {
$('#duration').text($video[0].duration);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="video_container">
<video poster="http://media.w3.org/2010/05/sintel/poster.png" preload="metadata" controls="" width="400">
<source type="video/mp4" src="http://media.w3.org/2010/05/sintel/trailer.mp4" id="mp4"></source>
<source type="video/webm" src="http://media.w3.org/2010/05/sintel/trailer.webm" id="webm"></source>
<source type="video/ogg" src="http://media.w3.org/2010/05/sintel/trailer.ogv" id="ogv"></source>
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
</div>
<div>Total duration : <span id="duration"></span></div>
you need a listener to get the duration of a video
var videoTime = 0;
var currentvideo = document.getElementById('video');
currentvideo.addEventListener('play', function() {
videoTime= currentvideo.duration;
console.info(videoTime) // get the duration
});

Categories

Resources