YouTube IFrame API on Internet Explorer and Firefox

More of an "answer" than a "question", but not having found this elsewhere I'm posting it here.

I was having difficulty initializing the iFrame API in all versions of IE and Firefox, with a somewhat custom implementation. Basically, it would load the API, but wouldn't create the player object.

After a bit of trial and error, I finally figured out it wasn't working because the div ID I was passing to the object had its CSS visibility set to 'none'. Once it was set to 'visible' the whole thing worked. After that I tried setting the div CSS to 'display:none' (the app required the video to be hidden until requested by the user) which also caused the iFrame API to fail silently (never calling back 'onPlayerReady').

So, long story short, when using the YouTube iFrame API to initialize on a div that you want to remain hidden until later, use a CSS technique like absolute positioning to push it off screen until you want it later. Also, found that once the player object is initialized and 'onPlayerReady' has been called you could turn display on and off all day long and everything would still work as expected.

Answers


You should leave the player conainer empty e.g.

<div class="myPlayerContainer"></div>

and when you want to show it just append it to container:

$('#showVideoBtn').click(function(){
    $('.myPlayerContainer').show().append('~ code of youtube iframe ~');
});

Yotam is right, look at the following:

HTML:

<button onclick="toggleYoutube();">show / hide</button>
<div id="youtube"></div>

JS ( using jQuery ):

var visible = false;
function toggleYoutube() {
    visible = !visible;
    if ( visible ) {
        $("#youtube").append( '<iframe id="video" width="640" height="360" src="http://www.youtube-nocookie.com/embed/cjvIeNt93nc?rel=0" frameborder="0" allowfullscreen></iframe>' );
    } else {
        $("#video").remove();
    }
}

See full code at http://jsfiddle.net/wFVhT/2/


Need Your Help

How to implement a loading animation when navigating in a iPhone app?

iphone animation

It seems like a pretty simple problem, but I have been unable to find any good answers.