Create a YT.Player object from an iframe in HTML by passing a DOM object

I have a built-in youtube video iframe in my html that I need to stop programmatically, but I cannot set the iframe id. Therefore, I am trying to create a youtube object by passing the DOM element to the YT.Player constructor, and not the iframe id, as indicated in the docs , I also added '? Enablejsapi = 1 'at the end of my iframe src url.

I downloaded youtube js api at the top of my js file using the following code:

var tag = document.createElement('script');
tag.src = "http://www.youtube.com/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 am assuming that somehow I am confusing an instance of an object, but I do not know how to do it correctly. How to create a YT.Player object without passing an id iframe constructor? Thanks for any help.

+3
1

-- .

​​ :

function onMyPlayerReady(event) { event.target.stopVideo(); }

yt.player :

new YT.Player($('iframe').get(0), { events: { 'onReady': onMyPlayerReady } });
+3

All Articles