With this code the video pauses as soon as I scroll. I want to pause the video when it goes out of view instead. How do I do this?
//This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//This function creates an <iframe> (and YouTube player)
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('video', {
    height: '100%',
    width: '100%',
    videoId: 'V6Y-ahQFQDA',
    playerVars: {
        'start': '1',
        'color': 'white',
        'controls': '1',
        'showinfo': '0'
    },
    events: {
      'onReady': playOnScroll,
      'onStateChange': playOnScroll
    }
  });
}
The part before is to load the video. I think my problem is in this if else statement. As soon as I start to scroll the log starts commanding paused, and I can't get it to work.
function playOnScroll() {
  var video = document.getElementById('video');
  var x = video.offsetLeft,
      y = video.offsetTop,
      w = video.offsetWidth,
      h = video.offsetHeight,
      r = x + w, //right
      b = y + h, //bottom
      visibleX,  visibleY,  visible;
      visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
      visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
      visible = visibleX * visibleY / (w * h);
  var percent = 0.6;
  var inView = visible > percent;
      if (inView) {
          console.log('play');
          player.playVideo();
      } else {
          console.log('paused');
          player.pauseVideo();
      }
}
window.addEventListener('scroll', playOnScroll, false);
window.addEventListener('resize', playOnScroll, false);