MarioD MarioD - 1 year ago 177
Javascript Question

Youtube API Dynamic iFrame

I'm trying to load a youtube video dynamically (iframe is generated on click after the page has loaded) with the ability to control the playback using the Youtube API.

What I have found is that if the iFrame is not present on the page when the API is loaded I can't seem to get the controls to work. What am I doing wrong? (I would like to avoid a solution that includes having the iframe present on the page when it is loaded)

Here's some example code: (Click on the black box to generate the iframe and play the video. Once the video is playing try to hit the pause button)

How could I bind the API to the iframe once it has been created on click so that the pause button works?

'use strict';

var player;

// Call the youtube api
var tag = document.createElement('script'); = 'iframe-demo';
tag.src = '';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Is the api ready
function onYouTubeIframeAPIReady() {
console.log('api is ready');

(function() {

var youtube = document.querySelectorAll( ".youtube" );

for (var i = 0; i < youtube.length; i++) {

youtube[i].addEventListener( "click", function() {

var iframe = document.createElement( "iframe" );

iframe.setAttribute( "id", "test-api" );
iframe.setAttribute( "frameborder", "0" );
iframe.setAttribute( "allowfullscreen", "" );
iframe.setAttribute( "src", ""+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1&enbalejsapi=1" );

this.innerHTML = "";
this.appendChild( iframe );

player = new YT.Player('test-api');

} );


var pause = document.querySelector('.pause');

pause.addEventListener('click', function() {


Any help would be greatly appreciated,

Answer Source

Small typo in enbalejsapi=1 should be enablejsapi=1

Add iframe sandbox attributes so that outer script can access the iframe

iframe.setAttribute( "sandbox", "allow-same-origin allow-scripts" );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download