youtube onStateChange event is not working

Go To


I have been bashing my head against this for a while now and need some fresh eyes:

I am trying to use the youtube JS api to call a function when the embedded videos state changes. But for some reason the event dosnt seem to be firing and I'm not getting any error in the console.


<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="630" height="350" id="bannerVideo">
    <param name="movie" value="" />
    <param name="allowfullscreen" value="true" />
    <param name="allowscriptaccess" value="always" />
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="" width="630" height="350">
        <param name="allowfullscreen" value="true" />
        <param name="allowscriptaccess" value="always" />
        <a href="">
            <img src="" alt="Get Adobe Flash player" />
        <!--[if !IE]>-->


function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("bannerVideo");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    //ytplayer.addEventListener("click", function(){alert('click');});

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

Example site:

The code I am using is a direct copy & paste from the youtube api site and I am using swf object to embed the code. I am using the static embedding because I will be changing some stuff out with php, but this shouldn't matter... right? I moved all the code out into its own file just for testing and its hosted on my development server so it shouldn't be a sandbox issue. I have also tried alerting after every line just to make sure the addEventListener function is not failing. (I have left the alerts in my example code but commented them out.)

After searching previous posts about this error I have found that they were all solved by adding the ID to the right element or parsing the callback function as a string. So I double and triple checking these things but that doesn't seem to be the issue.

Any help would be greatly appreciated.

2012-04-04 02:34
by Stewart Knapman


Have you tried initializing the flash embed using the SWFObject method (as outlined on the YouTube API)?

var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
                   "ytapiplayer", "425", "356", "8", null, null, params, atts);

Replace your tags with the above and configure it to your setup.

2012-04-04 03:12
by elkaz
Changing the embed method worked. Thanks for that.

Note to young players: use this way of embedding and not the static publishing method - Stewart Knapman 2012-04-04 03:29