Random videos background

1

How could I do that, with each access to the site, a different video appeared? I understand that there are codes that alter the background with images as below:

<script type="text/javascript">
window.onload = function(){

   var imgr = Math.round(Math.random()*4);

   var imgsrc = [
   'imagem1.jpg',
   'imagem2.jpg',
   'imagem3.jpg'
   ];
    document.getElementById('eximg').src = imgsrc[imgr];  
}
</script>
<img id="eximg"/>

But how would I apply to videos?

<video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="mp4/fundo.mp4" type="video/mp4">
</video>

PS: I ask that only people who understand the subject vote to close or indicate as a duplicate, because one case is an image and the other is a video and if they do, please give me an example, since many people, like this like me, do not have much experience in Jquery or Javascript and see this as differentiated cases.

    
asked by anonymous 17.07.2018 / 12:03

2 answers

1

My friend, just follow the same reasoning applied in the images, what changes is that you will change in src of the video. Using Jquery would look like this:

$('document').ready( function(){

   var video = Math.round(Math.random()*2);

   var videoaleatorio = [
   'fundo.mp4',
   'fundo2.mp4',
   'fundo3.mp4'
   ];
     $('source').attr('src', 'mp4/'+videoaleatorio[video]); 

console.log('endereço do video selecionado: '+ $('source').attr('src'));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><videoplaysinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="" type="video/mp4">
</video>
    
17.07.2018 / 13:25
0

You could save the urls of the videos to a database, and use the Math.random () to make the exchange of URLs

An example using array (as database):

let urls = 
[
    'http://meuvideo.com/1',
    'http://meuvideo.com/2',
    'http://meuvideo.com/3',
    'http://meuvideo.com/4',
    'http://meuvideo.com/5',
];


function maxAndMin(max){
  return Math.floor(Math.random() * max);
}


console.log(urls[maxAndMin(urls.length)]);
    
17.07.2018 / 12:37