I have an embedded youtube video iframe in my html that I need to stop programatically, but I am unable to set the id of the iframe. Therefore I am trying to create the youtube object by passing the DOM element to the YT.Player constructor rather than the iframe id, as specified in the docs. I have also appended '?enablejsapi=1' to the end of my iframe src url.
I have loaded the youtube js api at the top of my js file using the following code:
var tag = document.createElement('script');
tag.src = "";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubePlayerAPIReady(){ console.log('yt api ready'); }
After that I have the following code:
$(function(){
$('a.close').click(function(){
var player = new YT.Player($('iframe').get(0));
player.stopVideo();
});
})
I get the output:
yt api ready
Uncaught TypeError: Object [object Object] has no method 'stopVideo'
I'm assuming I'm screwing up the object instantiation somehow, but I don't know how to do this correctly. How do I create a YT.Player object without passing the constructor the iframe id? Thanks for any help.
I have an embedded youtube video iframe in my html that I need to stop programatically, but I am unable to set the id of the iframe. Therefore I am trying to create the youtube object by passing the DOM element to the YT.Player constructor rather than the iframe id, as specified in the docs. I have also appended '?enablejsapi=1' to the end of my iframe src url.
I have loaded the youtube js api at the top of my js file using the following code:
var tag = document.createElement('script');
tag.src = "http://www.youtube./player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubePlayerAPIReady(){ console.log('yt api ready'); }
After that I have the following code:
$(function(){
$('a.close').click(function(){
var player = new YT.Player($('iframe').get(0));
player.stopVideo();
});
})
I get the output:
yt api ready
Uncaught TypeError: Object [object Object] has no method 'stopVideo'
I'm assuming I'm screwing up the object instantiation somehow, but I don't know how to do this correctly. How do I create a YT.Player object without passing the constructor the iframe id? Thanks for any help.
Share Improve this question edited Apr 22, 2012 at 19:38 Tuck asked Apr 20, 2012 at 16:01 TuckTuck 4821 gold badge8 silver badges15 bronze badges1 Answer
Reset to default 3I needed to move the stop video call into the player object's ready event. The following changes fixed it for me
Added the following function:
function onMyPlayerReady(event) { event.target.stopVideo(); }
And changed the yt.player constructor to:
new YT.Player($('iframe').get(0), { events: { 'onReady': onMyPlayerReady } });