Random site background videos

Asked

Viewed 56 times

1

How could I make it so that, with every access to the site, a different video would appear? I understand that there are codes that change 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 duplicate, because one case is image and the other is video and if they do so, please give me an example, because many people who, just like me, you don’t have much experience in Jquery or Javascript and see this as differentiated cases.

  • 2
  • Just a quick comment. You need to dynamically select the videos in your directory, and I remember that there is the Random method in Javascript. Think about concatenating the video name into two variables for source assignment, something like video + 1 + mp4.

  • Guys. Sorry, my strong is not Jquery. How would I apply the link example to videos? Because a case is image (background) and in mine is video. Could you give me an example?

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>
<video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="" type="video/mp4">
</video>

  • 1

    Perfect Jorge. It worked! Thank you very much!!!

  • 1

    For nothing! Good luck! D

0

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

An example using array (as a 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)]);

  • Hi Lucas. How would I apply the code I passed? Because I don’t have much experience in Jquery or Javascript.

  • What video urls are?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.