Reputation: 95
I'm trying to set up an array of videoId's to be able to choose from to be randomly loaded. I tried to add the videos array as a videoId, and it didn't work. I'm kind of a JS newb, so I'm not really sure what it is I should be passing back for this. I got as far as this:
<div id="player"></div>
<script>
function rotateYT() {
var videos = [
'ZMnjkcvjN-E',
'RFQfSMbLCWw',
];
var index=Math.floor(Math.random() * videos.length);
}
// 2. 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);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '300',
width: '300',
videoId: videos[index], //where I'm trying to get the random videos
events: {
'onReady': onPlayerReady,
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
event.target.mute();
event.target.setPlaybackQuality('small');
}
</script>
Upvotes: 0
Views: 375
Reputation: 781088
The function needs to return the selected video ID:
function rotateYT() {
var videos = [
'ZMnjkcvjN-E',
'RFQfSMbLCWw',
];
var index=Math.floor(Math.random() * videos.length);
return videos[index];
}
Then you need to call it in onYouTubeIframeAPIReady
:
function onYouTubeIframeAPIReady() {
var videoID = rotateYT();
player = new YT.Player('player', {
height: '300',
width: '300',
videoId: videoID,
events: {
'onReady': onPlayerReady,
}
});
}
Upvotes: 2