title: Pause youtube and/or vimeo video in Iframe when onblur with javascript
body: <p>I would like to pause the video when the user click on another tab in their browser. I have tried to do this with Youtube and Vimeo.</p>
  
  <p>This is the basic idea behind the javascript:</p>
  
  <p>For Youtube:</p>
  
  <pre><code>//YouTube
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  
  var youtubePlayer;
  var onYouTubeIframeAPIReady = function() {
   youtubePlayer = new YT.Player('youtube', {
     height: '390',
     width: '640',
     videoId: 'sXtekwuT8R0',
     events: {
       'onReady': onPlayerReady,
       'onStateChange': onPlayerStateChange
     }
   });
  };
  
  var onPlayerReady = function(event) {
   event.target.playVideo();
  };
  
  var onPlayerStateChange = function(event) {
   if (event.data == YT.PlayerState.PLAYING) {
    parent.focus();
     window.onblur = function() {
       status.text("You went away!");
       youtubePlayer.stopVideo();
     };
   }
  };
  </code></pre>
  
  <p>For Vimeo (using their Froogaloop library):</p>
  
  <pre><code>$(function() {
    //Vimeo
    var iframe = $('#vimeo');
    var vimeoPlayer = $f(iframe[0]);
    var status = $('#status');
  
    vimeoPlayer.addEvent('ready', function() {
      vimeoPlayer.addEvent('play', function(){
        status.text("Playing!");
        parent.focus();
        window.onblur = function() {
          status.text("You went away!");
          vimeoPlayer.api("pause");
        };
      });
    });
  });
  </code></pre>
  
  <p>Here are some codepen examples of these attempts:</p>
  
  <p>Youtube:
  <a href="http://codepen.io/earlonrails/pen/jugAm" rel="nofollow">http://codepen.io/earlonrails/pen/jugAm</a></p>
  
  <p>Vimeo: 
  <a href="http://codepen.io/earlonrails/pen/KBAmd" rel="nofollow">http://codepen.io/earlonrails/pen/KBAmd</a></p>
  
  <p>Both examples will work if after I click the play button, I click on the parent document of the iframe then click a different window or tab. The Youtube example will also work when it is first loaded, but not if you click the play then pause then play. I believe both of these problems are due to the fact that you are clicking the iframe, therefore the event either is trigger at the same time or cannot be triggered because the event can't be captured there. I thought using the postMessages sent through the iframes along with callbacks would make this work, but alas I have not been able to figure this out.</p>