Getting YouTube videos to PAUSE nice with each other
I don’t know if YouTube had in mind for us to put more than one video on a page. It didn’t seem like it when I set out to make one player pause other videos when it was played. By the end I found that YouTube had enough hooks in the player API to make it possible. Barely.
Contributing factor: I was looking to accomplish this with the bare-bones elements without any plug-ins such as “swfobject.” I googled and binged and asked Jeeves but it seemed no one had posted a way of doing this. Hence this blog post. Feel free to use the code below if you need.
View Demo | View Code
In general:
I enabled YouTube’s JavaScript API (shown below in yellow) so that the videos will let me know when they are ready for instructions. When that occurs I tell the videos to report back if their state changes from, oh say, stopped to playing. When that happens it sends a notice for all other videos to check themselves and PAUSE if they are PLAY-ing.
In specific:
There are two keys to making this work that were not obvious in the beginning. The first was that I needed to put a “playerapiid” in the URL to the video to get it to pass it back when it calls the first function (onYouTubePlayerReady). The last function uses this ID to see if it matches any players ID’s that are on the page. For any player that doesn’t match it will check to see if it is playing and then pause it if it is. You can see the “playerapiid” highlighted below in green.
The second issue that I ran into is that the player does not pass it’s ID when it calls the second function (“onStateChange”) so the function that runs needs to first acquire the ID of the player. This is why I said that YouTube barely added enough to make this possible. If the “onStateChange” event would not only pass the STATE of the player but also the ID then I would not need to use a function as the second parameter to acquire the ID.
In scriptcific:
//You will have multiple OBJECTS on your page - I am only showing one here:
<param value=”always” name=”allowScriptAccess“/>
<script type=”text/javascript”>//Be sure that jQuery is added to your page
function onYouTubePlayerReady(playerId) {
var player = $(‘#’+playerId)[0];
//…that passes the player’s ID through to the next function
player.addEventListener(‘onStateChange’,'(function(state){ return playerState(state,”‘+playerId +'”);})’);}
function playerState(state, playerId) {
if(state == 1){
$(‘.vid-object’).each(function(){ var thisID = $(this).attr(‘id’), ytplayer1 = document.getElementById(thisID), ytp1State = ytplayer1.getPlayerState();
if(ytp1State == 1 && ytplayer1.id != playerId){
ytplayer1.pauseVideo();
}});}}