soren.qvist
soren.qvist

Reputation: 7416

YouTube Javascript API onstateChange event problems

My javascript:

function onYouTubePlayerReady()
{
  playerObj = document.getElementById("player_embed");
  playerObj.addEventListener("onStateChange", test);

  // Make sure the document is loaded before any DOM-manipulation
  $(document).ready(function() {

      // Update player information every 500ms
      setInterval(updatePlayerInfo, 500);

  });
}

function test(newState)
{
    alert(newState);
}

My videos are loaded correctly and I can control fine them through my javascript. However the onStateChange event never seems to trigger. It never comes up with an alert when I'm playing/stopping/pausing videos etc. Anyone with a solution/similar problem?

Upvotes: 1

Views: 3392

Answers (2)

Stergios Zg.
Stergios Zg.

Reputation: 662

This format is for JQuery but the logic is same, create a function inside onYouTubePlayerReady to pass the playerId

$(document).ready(function() {              
    onYouTubePlayerReady = function(playerId) {
        eventHandler=function(state){onStateChangeID(state,playerId);}
        playerObj = document.getElementById("player_embed");
        playerObj.addEventListener('onStateChange','eventHandler',false);
    }
    onStateChangeID=function(newState,playerId) {
        console.log("onStateChange: ("+playerId+") " + newState);
    }
});

Upvotes: 0

leebriggs
leebriggs

Reputation: 3257

You must pass the function name as a string to addEventListener.

playerObj.addEventListener("onStateChange", "test");

Upvotes: 4

Related Questions