最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how can I pause a youtube embed when a user scrolls away - Stack Overflow

programmeradmin3浏览0评论

I have been trying to look for help with respect getting a video to pause when a user scrolls away. I have already been able to find help for html5 videos but now I also need to know how the youtube API can be used for the same.

the html structure I have that embeds the YouTube is as follows

     <div class="ytube-container">

     <iframe id="vplayer" 
      src="//www.youtube/embed/qKaMgJwBItM?modestbranding=1&showinfo=0&modestbranding=0&controls=1&rel=0&autoplay=1&vq=hd720" 
    frameborder="0"webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

    </div>

I used the following for html5 - does the youtube API have a very different method to do the same?

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

    function checkScroll() {

    for(var i = 0; i < videos.length; i++) {
    var video = videos[i];
    var x = 0,
    y = 0,
    w = video.offsetWidth,
    h = video.offsetHeight,
    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 + w;
    b = y + 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) {
    video.play();
    } else {
    video.pause();
    }
    }

    }

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

    </script>  

I am not sure I understand how to entirely use the Youtube API I was able to find a code that stops one player if the other is playing but I dont see how that can be manipulated to achieve what I need.

<script>

players = new Array();

function onYouTubeIframeAPIReady() {
var temp = $("iframe.vplayer");
for (var i = 0; i < temp.length; i++) {
    var t = new YT.Player($(temp[i]).attr('id'), {
        events: {
            'onStateChange': onPlayerStateChange
        }
    });
    players.push(t);
}

}
onYouTubeIframeAPIReady();


function onPlayerStateChange(event) {

if (event.data == YT.PlayerState.PLAYING) {
    var temp = event.target.a.src;
    var tempPlayers = $("iframe.yt_players");
    for (var i = 0; i < players.length; i++) {
        if (players[i].a.src != temp) players[i].stopVideo();

    }
}
}

I have been trying to look for help with respect getting a video to pause when a user scrolls away. I have already been able to find help for html5 videos but now I also need to know how the youtube API can be used for the same.

the html structure I have that embeds the YouTube is as follows

     <div class="ytube-container">

     <iframe id="vplayer" 
      src="//www.youtube./embed/qKaMgJwBItM?modestbranding=1&showinfo=0&modestbranding=0&controls=1&rel=0&autoplay=1&vq=hd720" 
    frameborder="0"webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

    </div>

I used the following for html5 - does the youtube API have a very different method to do the same?

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

    function checkScroll() {

    for(var i = 0; i < videos.length; i++) {
    var video = videos[i];
    var x = 0,
    y = 0,
    w = video.offsetWidth,
    h = video.offsetHeight,
    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 + w;
    b = y + 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) {
    video.play();
    } else {
    video.pause();
    }
    }

    }

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

    </script>  

I am not sure I understand how to entirely use the Youtube API I was able to find a code that stops one player if the other is playing but I dont see how that can be manipulated to achieve what I need.

<script>

players = new Array();

function onYouTubeIframeAPIReady() {
var temp = $("iframe.vplayer");
for (var i = 0; i < temp.length; i++) {
    var t = new YT.Player($(temp[i]).attr('id'), {
        events: {
            'onStateChange': onPlayerStateChange
        }
    });
    players.push(t);
}

}
onYouTubeIframeAPIReady();


function onPlayerStateChange(event) {

if (event.data == YT.PlayerState.PLAYING) {
    var temp = event.target.a.src;
    var tempPlayers = $("iframe.yt_players");
    for (var i = 0; i < players.length; i++) {
        if (players[i].a.src != temp) players[i].stopVideo();

    }
}
}

Share Improve this question edited Aug 6, 2014 at 21:18 new_frontenddev asked Aug 6, 2014 at 0:19 new_frontenddevnew_frontenddev 1733 gold badges7 silver badges21 bronze badges 3
  • You can start by making a real player with the api developers.google./youtube/iframe_api_reference?hl=fr – mpgn Commented Aug 6, 2014 at 9:23
  • is that even suppose to help me ? If I really was able to interpret their guide as well as some of the people here, I wouldn't ask a question – new_frontenddev Commented Aug 6, 2014 at 21:21
  • Just take a look at my answer, because yes it's suppose to help you. – mpgn Commented Aug 6, 2014 at 22:40
Add a ment  | 

1 Answer 1

Reset to default 12

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./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)

发布评论

评论列表(0)

  1. 暂无评论