YouTube IFrame API on Internet Explorer and Firefox
Asked Answered
K

2

23

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.

Knacker answered 3/1, 2013 at 21:37 Comment(2)
That's a good point, and it's also worth mentioning that if you have a visible player, then set display: none on the player (or a container), the player is effectively purged by the browser. You would not be able to later set display: inline and reuse the same player instance. Moving the player out of the viewport is the answer here, too.Sweatband
Please stick to the format. Even if you know the answer to what you're posting, post it as a question phrased as a question, and post an answer. (The question web form allows you to post both simultaneously, if you want, so there is no reason to put the answer into the question post.)Sy
S
1

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 ~');
});
Sperling answered 28/5, 2013 at 9:55 Comment(0)
E
1

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/

Erlindaerline answered 28/5, 2013 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.