Razzer
Razzer

Reputation: 884

JS & HTML - how can i embed a random video?

I want to play a random video on my website. But I don't know how I can make that, because I'm a noob with HTML & JSS. I searched for a simple way to do that, but I can't find a solution.

Thats my code on the Website, where the different videos should come:

<div class="bg-video-wrapper" id="video-background-1">
     <div class="bg-video-overlay bg-dark-alfa-50"></div>
          </div>

And thats my code for "video-background-1":

var videobackground_1 = new $.backgroundVideo($('#video-background-1'), {
        "align": "centerXY",
        "width": 1920,
        "height": 1080,
        "path": "assets/videos/",
        "filename": "trailer3",
        "types": ["mp4", "ogg", "webm"],
        "autoplay": true,
        "loop": true

Is it possible to add a filename to "trailer3" with a comma or something? Is there an easy way to add a video and it get picked randomly which one is played?

Upvotes: 0

Views: 178

Answers (2)

Nathan Chu
Nathan Chu

Reputation: 657

Building a little on @ItGrunt's answer (upvote his, too, if you found mine helpful):

You would have to implement something like this:

var videobackground_1 = new $.backgroundVideo($('#video-background-1'), {
        "align": "centerXY",
        "width": 1920,
        "height": 1080,
        "path": "assets/videos/",
        "filename": ["trailer1", "trailer2", "trailer3"][Math.floor(Math.random()*3)],
        "types": ["mp4", "ogg", "webm"],
        "autoplay": true,
        "loop": true

You could also write a function for this to clean your code up like the following:

function random(a) {
  return a[Math.floor(Math.random()*(a.length))]
}
var videobackground_1 = new $.backgroundVideo($('#video-background-1'), {
        "align": "centerXY",
        "width": 1920,
        "height": 1080,
        "path": "assets/videos/",
        "filename": random(["trailer1", "trailer2", "trailer3"]),
        "types": ["mp4", "ogg", "webm"],
        "autoplay": true,
        "loop": true

Upvotes: 1

It Grunt
It Grunt

Reputation: 3378

How many videos do you have? You could build a hashmap with a numeric key <int, path to video>

then use a random number function for example:

Math.floor(Math.random() * 11); //gets 0-10  

and use that number as a key to get filename from the hashmap to use in the request...

Upvotes: 2

Related Questions