user28240
user28240

Reputation: 121

Nightmare with YouTube API and the playVideo to work

I have tried to implement the YouTube API into my site, and it was working fine up until a few days ago, and after hours and hours of no progress, I have made a fiddle with a basic setup, and I can't get it to work when you have an iFrame already embedded in the page.

 var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('testplayer');
}
function playthevideo() {
    player.playVideo();
};
jQuery( document ).ready(function() {
    jQuery('.testing').on('click', playthevideo);
});

http://jsfiddle.net/parvavilla/GXC4e/

When you click the button, the console says:

Uncaught TypeError: Object #<S> has no method 'playVideo' 

Any ideas what I have done wrong in this fiddle?

Upvotes: 0

Views: 200

Answers (1)

Brad
Brad

Reputation: 163602

The problem is that you are already loading a video via iframe. The API doesn't expect that. What you need instead is just a normal container. In your HTML:

<div id="testplayer"></div>

Then in your JavaScript:

player = new YT.Player('testplayer', { videoId: 'M7lc1UVf-VE' });

JSFiddle: http://jsfiddle.net/GXC4e/2/

Upvotes: 2

Related Questions