Now there’s a long-winded title for you!
Yes, I’m having problems (IE-specific) when closing an overlay that contains a YouTube video – the movie just keeps on playing in the “background”.
My current setup was pretty simple – basically just pasting the embed code from YouTube into a <div> element that I had designated as being the overlay with jQuery Tools. But in this case, the KISS method was not going to work!
I took the initial steps in re-working what I had originally:
- Created single overlay
<div>element that will be used for all the movies instead of creating an overlay for each. - For each video, a hidden input field was created that stored the value (unique ID) of said video.
- If one or more videos was present in the feed, the first one in the list was inserted into the overlay
<div>using swfobject.
So far so good. But now for the fun stuff – being able to control the YouTube player on the fly so that I can switch from video to video – and – be able to control the controls (play, pause, stop, etc.). For this, YouTube provides a rich JavaScript API.
The call back function onYouTubePlayerReady(playerId) is fired whenever the video player is active, so in my case, this function was getting fired each time I opened one of the video overlay’s. This function returns a reference to the player which is needed in order to control it.
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
}
From there its a pretty simple process – adding in the necessary player controls (play and pause) was about all that was needed.
However, when I tested in IE, my API function calls kept throwing errors, and I couldn’t for the life of me figure out why … until about an hour of testing later!
Because of where my video feed is located, I needed to move the overlay that the video was inserted into to the end of the DOM – which I accomplished with JavaScript:
$('#videofeed').appendTo('body');
This turned out to be the culprit. For some reason, when this action occurred (after the video has been inserted already by swfobject, my player reference variable lost all reference to the actual YouTube player). This wasn’t a problem in the other browsers I tested in – it just seemed to be an IE-specific one. Anyhow, the fix for this was easy – I moved the overlay in the DOM first and then inserted the video.
Quite a frustrating process, all in all, but the silver lining is that I got to use the YouTube JavaScript API for the first time and it should prove to be useful in projects I work on in the future.
Time for a coffee – I need it!