Reputation: 193
I seem to be having an issue adding an eventlistner to my YT.player.
var ytapi = document.createElement('script');
ytapi.src = "https://ww" + "w.youtube" + ".com/iframe_api";
var scriptref = document.getElementsByTagName('script')[0];
scriptref.parentNode.insertBefore(ytapi, scriptref);
window.players = [];
function onPlayerStateChange(event) {
switch(event.data) {
case YT.PlayerState.ENDED:
alert('VIDEO IS ENDED');
case YT.PlayerState.CUED:
alert('VIDEO IS CUED');
case YT.PlayerState.PAUSED:
alert('VIDEO IS PAUSED');
break;
}
};
window.onYouTubeIframeAPIReady = function() {
jQuery('iframe[src*="youtube.com"]').each(function() {
var id = jQuery(this).attr('id');
window.players[id] = new YT.Player(id);
window.players[id].addEventListener('onStateChange','onPlayerStateChange');
});
};
OnStateChange is not being triggered, but
If i in the browser console do
window.players[id].addEventListener('onStateChange','test');
function test(event){alert(event.data)};
It works?
Aren't I doing the exact same in the code? so why does it only work in console?
Upvotes: 0
Views: 47
Reputation: 10384
That happens because addEventListener(<string>, <string>)
isn't a function, as stated here.
As you can read, about the second parameter of the method:
This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.
So a string isn't accepted. Probably you meant to pass the test
function variable reference, and not the test
string.
So, just drop quotes:
addEventListener('onStateChange', test);
Note: Some javascript functions also accept strings in place of functions, such as eval
and setTimeout
. But the use is discouraged
Upvotes: 1