0

I'm trying to capture the YT object. The onYouTubePlayerReady() functions is called but I can't seem to do anything with the object.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("swfobject", "2.2");
</script>
<script type="text/javascript">
    function onYouTubePlayerReady (playerID)
    {
        ytplayer = document.getElementById(playerID);
    }

    function play ()
    {
        if (ytplayer)
        {
            ytplayer.playVideo();
        }
    }
    play();
</script>

ytplayer is referenced to the DOM and not the video itself (play therefor throws Uncaught TypeError: Object # has no method 'playVideo', but this is basically the example given by google.

What am I doing wrong?

Daniel
  • 3,726
  • 4
  • 26
  • 49

2 Answers2

1

You are calling play(); as soon as the page loads.

But it takes some time to load youtube player and thus function onYouTubePlayerReady gets called after some time.

Since, you define ytplayer in onYouTubePlayerReady, you cannot use ytplayer before onYouTubePlayerReady gets called. Also, ytplayer should be made global so that both functions can use it.

Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

I don't see where you're initializing your video player at all in your above code. The code below is working fine in Firefox. Substitute the video ID of the video you would like to play in place of [YOUR_VIDEO_ID] below and you should be all set. Can also confirm that the code below works like a champ in IE and Chrome as well.

<div id="video" class="overlay">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
  <div id="ytapiplayer"></div>
  <script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: 'myytplayer' };
    swfobject.embedSWF("http://www.youtube.com/v/[YOUR_VIDEO_ID]?enablejsapi=1&playerapiid=ytplayer&version=3", "ytapiplayer", "640", "360", "8", null, null, params, atts);

    function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");

      ytplayer.addEventListener('onStateChange','onytplayerStateChange');
    }

    function onytplayerStateChange(newState) {
      alert("Player's new state: "+newState);
    }

    function play() {
      if (ytplayer) {
        ytplayer.playVideo();
      }
    }
  </script>
  <a href="javascript:void(0)" onclick="play()">Play</a>
</div>

I think what you're missing is that you need to reference the "playerId" by whatever you passed in to the object initialization attributes (var atts = ...) line. Doing a little bit of testing does reveal that the "onYouTubePlayerReady" function does not actual pass a valid id value that can be used to perform the DOM lookup.