0

I need to display a random youtube video from a selection when the page loads. I found the question below very helpful however I can't figure out how to get it to autoplay. I've tried adding

&autoplay=1

after "videos[index]" but I can't get it to work / don't know if I am putting it in the wrong place. Any help would be much appreciated.

Trying to display a random video on page load

$(document).ready(function() {

var videos = [
'pRpvdcjkT3k',
'Te4wx4jtiEA',
'efTj6UYzvk4'
];

var index=Math.floor(Math.random() * videos.length);
var html='<div id="video"><h3>Random Video</h3><iframe width="720" height="480" src="http://www.youtube.com/embed/ ' + videos[index] + ' + "&autoplay=1" " frameborder="0" allowfullscreen></iframe></div>';
document.write(html);

});//-->
Community
  • 1
  • 1
user1688604
  • 103
  • 1
  • 2
  • 9
  • 1
    Should be fine, could you paste your code to see what issues you might be having? – David G Mar 02 '14 at 14:18
  • Sure, tried a few varations as I'm not sure I have the syntax right, page is loading and loading but not playing, videos load fine when I take the autoplay out – user1688604 Mar 02 '14 at 14:23

2 Answers2

2
$(document).ready(function() {

var videos = [
'pRpvdcjkT3k',
'Te4wx4jtiEA',
'efTj6UYzvk4'
];

var index=Math.floor(Math.random() * videos.length);
var html='<div id="video"><h3>Random Video</h3><iframe width="720" height="480"   src="http://www.youtube.com/embed/' + videos[index] + '?autoplay=1" frameborder="0" allowfullscreen></iframe></div>';
document.write(html);

});

'?' instead of '&'

user1688604
  • 103
  • 1
  • 2
  • 9
-2

Sorry to say but your method is wrong. This is not how you should request a random video from YouTube. You should use IFrame API so, it works better than this method.

This is how you can use IFrame API: https://stackoverflow.com/a/7513356/15327265

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 21 '21 at 04:56