Question

http://jsfiddle.net/y2Y5k/ I'm trying to make a simple youtube player with the javascript API and I'm doing something wrong.

In that fiddle, Im just using the exact code snippets from the documentation provided by google.

I loaded the api as a source.

I placed a div with the id 'player'.

What did I do wrong here?

<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 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: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

Was it helpful?

Solution

It is because Fiddle. All JavaScript you put in there is encapsulated in other functions (probably window.onload or something). Therefore Youtube can't get to your onYouTubeIframeAPIReady function.

Just try this outside Fiddle. It will work.

OTHER TIPS

On the top left side, from Frameworks & Extensions, select No wrap - in instead of onLoad.

That will give you the result as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top