Skip to content

Instantly share code, notes, and snippets.

@alishutc
Last active July 30, 2025 14:34
Show Gist options
  • Save alishutc/a6b1b0fc11a28a627897 to your computer and use it in GitHub Desktop.
Save alishutc/a6b1b0fc11a28a627897 to your computer and use it in GitHub Desktop.
Play a random embedded youtube video
<!DOCTYPE html>
<html>
<head>
<script>
var videos = ["https://www.youtube.com/embed/9bZkp7q19f0", "https://www.youtube.com/embed/dQw4w9WgXcQ"];
window.onload = function () {
var playerDiv = document.getElementById("random_player");
var player = document.createElement("IFRAME");
var randomVideoUrl = videos[Math.floor(Math.random() * videos.length)];
player.setAttribute('width', '640');
player.setAttribute('height', '390');
player.setAttribute('src', randomVideoUrl);
playerDiv.appendChild(player);
};
</script>
</head>
<body>
<div id="random_player" />
</body>
</html>
@arya-bhushan
Copy link

Cool:)

@cesarradtke
Copy link

cesarradtke commented Oct 30, 2017

Sorry my unknowingness, but where can I include autoplay feature (&autoplay=1) into this code?

player.setAttribute('autoplay', '1'); don't work for me.

@tsmith165
Copy link

@cesarradtke You can do so by adding the autoplay value to the URL. Here's a link to the possibilities for style changes for youtube embeds: https://developers.google.com/youtube/player_parameters

@MyPC8MyBrain
Copy link

MyPC8MyBrain commented Apr 25, 2018

can a title be added for each of the video from a parallel pre defined title list?

@mootjedepro
Copy link

you really tried to rickroll us

@ageofcontrol
Copy link

Thank you for the a good solid, basic code!

I'm working on making it choose a randomvideo every 30 seconds!

@xanshark
Copy link

Used a slightly edited version of this on my website that only requires the ID and not the full link, and disables the autoplay at the end.

<script>
     var videos = ["WDsP9r1oWjU", "LqWOZDIzVVQ"];
     window.onload = function () {
          var playerDiv = document.getElementById("random_player");
          var player = document.createElement("IFRAME");
          var randomVideoUrl = ["https://www.youtube.com/embed/"] + videos[Math.floor(Math.random() * videos.length)] + ["?&rel=0"];
          console.log(randomVideoUrl);
          player.setAttribute('width', '640');
          player.setAttribute('height', '390');
          player.setAttribute('src', randomVideoUrl);

          playerDiv.appendChild(player);
     };
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment