user246114
user246114

Reputation: 51631

YouTube player api - addEventListener() does not work for me?

I'm using the youtube player api. I'm following the doc here:

http://code.google.com/apis/youtube/js_api_reference.html

having a problem adding an event listener on the player, it seems to just get stuck there. I put an alert statement directly after, which never gets called:

ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
alert("I never get called...");

any idea why this would happen? Running it through FF chrome safari, same thing happens on all. Other player features all work fine. I'm using the swfobject version. I'm running this live from a server too. I don't get it.

Thanks

Upvotes: 3

Views: 9913

Answers (3)

hndcrftd
hndcrftd

Reputation: 3210

take a look at the source code of this page, may be it will get you going in the right direction. The number under the video is the state of the video caught and updated the way you are trying to implement

var ytplayer;

function onytplayerStateChange(newState) {
    document.getElementById('videoStatus').innerHTML = newState;
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById(playerId);
    ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
}

$(document).ready(function() {

    var params = {
        allowScriptAccess: "always"
    };

    var atts = {
        id: "ytplayer1"
    };

    swfobject.embedSWF("http://www.youtube.com/v/5dWnMu490Zk?rel=0&autoplay=1&enablejsapi=1&playerapiid=ytplayer1", "popupVideoContainer1", "853", "505", "9", null, {}, params, atts);

});
<div id="popupVideoContainer1">You need Flash and JavaScript in order to view the video.</div>
<div id="videoStatus">status</div>

Upvotes: 1

Peter Watts
Peter Watts

Reputation: 710

I think it's a bug. Here's the solution that worked for me:

In the Player URL, you must include a '&' after the ?. So the example is this:

VIDEO_ID?enablejsapi=1&playerapiid=ytplayer

But use this instead:

VIDEO_ID?&enablejsapi=1&playerapiid=ytplayer

(note the & before 'enable')

Doesn't make much sense, but it's working now :)

Upvotes: 0

trcarden
trcarden

Reputation: 891

Place your callback in the global namespace, eg window.onytplayerStateChange = function.

While its pretty crappy its one of the few ways i was able to successfully get the callback to work. I was told its because the addEventListener is a custom function overriding the native code that does a lookup via string in the global namespace.

Upvotes: 1

Related Questions