Ryan Fleury Ryan Fleury - 6 days ago 7
Javascript Question

YouTube API dynamically loading videos

-I want many videos loaded onto a page, nothing fancy

-Video ID is stored in a database -> $slide['message']

-I can get it to load only one video. The others are blank

-It is inside a loop, when the kind == youtube, it tries to put the video in.


if($slide['kind'] == 'youtube'){
?>
<li>
<div class="info<?php echo $count+1; ?>">
<h1><?php echo $slide['title']; ?></h1>
<div id="ytplayer<?php echo $count+1; ?>" class="youTube-viewer"></div>
<script>
var video = '<?php echo $slide['message']; ?>';
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer<?php echo $count+1; ?>', {
height: '365',
width: '648',
videoId: video,
playerVars: {
'rel': 0,
'enablejsapi': 1,
}
});
}
</script>
<h2><?php echo $slide['name']; ?></h2>
</div>
</li>
<?php
}

Answer

Using what jlmcdonald gave me as a hint, I got it to work, see the link to the fiddle below http://jsfiddle.net/AaGvt/

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

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '250',
    width: '500',
    videoId: 'u1zgFlCw8Aw',
    events: {}
  });

  player = new YT.Player('player2', {
    height: '250',
    width: '500',
    videoId: 'u1zgFlCw8Aw',
    events: {}
  });

  player = new YT.Player('player3', {
    height: '250',
    width: '500',
    videoId: 'u1zgFlCw8Aw',
    events: {}
  });

}

</script>

<div id="player"></div>
<div id="player2"></div>
<div id="player3"></div>

Through SQL requests and loops you can build the divs

<div id="player"></div>
etc...

And create the needed javascript

  player = new YT.Player('player', {
    height: '250',
    width: '500',
    videoId: 'u1zgFlCw8Aw',
    events: {}
  });
etc...
Comments