Search code examples
jsp-tagsyoutube-javascript-api

Youtube onYouTubePlayerReady() function not firing


This question has been asked many times before, however I couldn't solve it even after referring the solutions.

I have an embedded Youtube Player. I am following https://developers.google.com/youtube/js_api_reference#Examples.

Below is my JS code:

    var params = {
            scale:'noScale',
            salign:'lt',
            menu:'false',
            allowfullscreen :'true',
            wmode :'transparent',
            allowScriptAccess: 'always'
          };

    var atts = { id: "myytplayer" };

    swfobject.embedSWF("http://www.youtube.com/v/vPxGBYJ9Wt8?enablejsapi=1&playerapiid=ytplayer&version=3", "ytapiplayer", "560", "315", "8.0.0", null, null, params, atts);


    function onYouTubePlayerReady(playerId) {
      alert("youtube player ready");
      ytplayer = document.getElementById("myytplayer");
      ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    }

      var count = 0;

      function onytplayerStateChange(newState) {
          alert("inside");
        if (newState == 1){
          count = count + 1;

          //Trying to count the number of times video is played
        }
      }

I can watch the video, but I am not able to get any of the alert messages.

It is being served from a Web Server. Also, the JS code is written within a JSP page. What are the things I should check?

Update

I tried the same code in a separate fie and it works just fine.


Solution

  • I solved the problem by putting the window.onYouTubePlayerReady inside $(document).ready(function())