how can I pause a youtube embed when a user scrolls away

心已入冬 提交于 2019-12-03 21:24:25

You done a great job with HTML5 player and the function checkScroll().
It seem you have trouble to use it with the YouTube JS Player, well if you take the time to read the doc, you discover that the YouTube player is just an iframe.

Try this live example i made : http://jsbin.com/cocatuta/15/edit?js,output

So basically i just replace :

var videos = document.getElementsByTagName("video"), fraction = 0.8;

By this :

var videos = document.getElementsByTagName("iframe"), fraction = 0.8;

And add two function playVideo and pauseVideo.

function playVideo() {
  player.playVideo();
}

function pauseVideo() {
  player.pauseVideo();
}

Full code :

//play when video is visible
var videos = document.getElementsByTagName("iframe"), fraction = 0.8;

function checkScroll() {


  for(var i = 0; i < videos.length; i++) {
    var video = videos[i];

    var x = 0,
        y = 0,
        w = video.width,
        h = video.height,
        r, //right
        b, //bottom 
        visibleX, visibleY, visible,
        parent;


    parent = video;
    while (parent && parent !== document.body) {
      x += parent.offsetLeft;
      y += parent.offsetTop;
      parent = parent.offsetParent;
    }

    r = x + parseInt(w);
    b = y + parseInt(h);


    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);


    if (visible > fraction) {
      playVideo();
    } else {
      pauseVideo()

    }
  }

};

window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);

//check at least once so you don't have to wait for scrolling for the video to start
window.addEventListener('load', checkScroll, false);
checkScroll();

Hope it's help ! And yes, read the doc "is even supposed to help you" (eventually)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!