1

We have a number of clients who have youtube video advertisements. These are currently in a YouTube playlist, but by embedding the playlist, the same video is always displayed first on the website so we want to randomise which video is displayed on pageload from the playlist. I have a code snippet which will load a random video from the input video url however when the video is finished it does not move on to the next video in the list. Could anyone suggest how I can accomplish what I am trying to do? My code is below.

    <!-- Youtube video loop playlist -->
<script>
        var videos = ["https://www.youtube.com/embed/9bZkp7q19f0", "https://www.youtube.com/embed/dQw4w9WgXcQ", "https://www.youtube.com/embed/CzJ-h7W1hVw"];
        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', '528');
            player.setAttribute('height', '330');
            player.setAttribute('src', randomVideoUrl);
            playerDiv.appendChild(player);
        };
        onStateChange: function(e){
            var id = 'qzZuBWMnS08';

            if(e.data === YT.PlayerState.ENDED){
                player.loadVideoById(videos);
            }
        }
    </script>
<div id="random_player"></div>

Thank you in advance. Donna

Dtorr1981
  • 299
  • 2
  • 16

1 Answers1

2

The function loadVideoById can either get a single ID or a single video in an object syntax. It can't receive an array of videos or a playlist.

Here's my implementation http://jsfiddle.net/thatkookooguy/e11oy0eu/2247/ (code also embedded at the end)

Notice that the setTimeout is used since there's a bug with the youtube API. if you set either setShuffle or playVideoAt immediately, nothing happens (or the playlist resets and starts from the beginning).

You can add anything else you want to change in the player's playback options (shuffle, loop). If it doesn't work as is, try to add those parameters to the setTimeout as well.

reference: youtube API - setShuffle don't work

// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

// load the playlist
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    events: {
      'onReady': onPlayerReady
    },
    playerVars: {
      listType: 'playlist',
      list: 'PLOy0j9AvlVZPto6IkjKfpu0Scx--7PGTC'
    }
  });
}

// when the video player is ready, generate a random number, and play from that
function onPlayerReady(event) {
  // create a random number between 0 and 149
  num = Math.floor(Math.random() * 150);

  // the timeout is set because of a bug with the youtube API. if you do any of this line without it, it won't affect anything
  // see: https://stackoverflow.com/questions/12916017/youtube-api-setshuffle-dont-work
  setTimeout(() => {
    player.playVideoAt(num);
  }, 1000);
}
<div id="player"></div>
Thatkookooguy
  • 5,356
  • 1
  • 24
  • 47
  • Thank you :) However, I'm still having a problem. I have added my playlist ID into your code snippet but it still only loads the first video - Obviously your solution works with your playlist. So i'm baffled. See my snippet here: http://jsfiddle.net/Dtorr1981/e11oy0eu/2250/ – Dtorr1981 Apr 05 '18 at 10:10
  • @Dtorr1981 you just forgot to change to random numbers from `0 to 150` to `0 to 9` (your playlist only have 10 videos). Here is your snippet forked and fixed: http://jsfiddle.net/thatkookooguy/gwb1hk9q/1/ (please don't forget to mark my answer as the right answer if it helped you out :-)) – Thatkookooguy Apr 06 '18 at 06:46
  • I'm still struggling to get this to randomise - I'm using this within a Joomla installation and am seeing the following error: Uncaught ReferenceError: _ is not defined at onPlayerReady - Any suggestions? You can see the player in action here: https://www.outyego.com/staging/ – Dtorr1981 Apr 16 '18 at 07:38
  • There's a library called `lodash` on my original jsfiddle that you copied when you forked my jsfiddle. just replace the line `num = _.random(0, 9);` with `num = Math.floor(Math.random() * 10);` to use vanilla javascript. Changed that in my answer as well. – Thatkookooguy Apr 16 '18 at 08:29
  • Brilliant that seems to work - can you confirm however that the number should be the playlist number - 1. IN your example you have said the playlist num is 14 so -1 that should be 13? - Is it possible to also tune off autoplay? – Dtorr1981 Apr 16 '18 at 13:22
  • @Dtorr1981 yup. that was a mistake. `Math.random()` gives a random number between 0 and 1, **NOT** including 1. So it should be `Math.floor(Math.random() * playlist.length)`. That way, the number that will be generated is between 0 and `playlist.length` - 1. – Thatkookooguy Apr 16 '18 at 13:32
  • Thank you for the clarification - do you no if there is a way to turn off the autoplay function? – Dtorr1981 Apr 16 '18 at 14:03
  • @Dtorr1981 there's no autoplay here. The video is playing since we call `player.playVideoAt`. Sorry, I'm not sure how you can set a video without start playing it. – Thatkookooguy Apr 16 '18 at 14:13
  • Ah ok - is it possible to auto-mute it then? Thank you again for all of your help with this. :) – Dtorr1981 Apr 16 '18 at 14:16
  • 1
    `player.mute();`. you can add that just before the `player.playVideoAt` line. you're welcome! just don't forget to mark the answer as the acceptable answer :-) – Thatkookooguy Apr 16 '18 at 14:18
  • I've just spotted that there is no volume control on iPad devices, thus the video plays, but I cannot turn the volume up to hear it - is this anything you are aware off? – Dtorr1981 Apr 19 '18 at 08:11
  • https://stackoverflow.com/questions/31147753/youtube-iframe-embed-cant-control-audio-on-ipad – Thatkookooguy Apr 22 '18 at 14:24
  • Is there away I can allow the user to unmute it? At present the video plays but there is no option for it to be unmuted at all - thus muting the video programmatically is causing a problem. Either that, or pausing the random video after it starts to plat? I have tried player.pauseVideo(); within the code, but it either doesn't pause or prevents the random video loading completely? – Dtorr1981 Apr 23 '18 at 07:22