2

I want to stop the video when scrolled bottom of it. In my code the video will start playing when scrolled from the top of it, but it will continues playing when I scrolled to bottom of video. I want to stop the video after scrolled bottom.

This is the code:

<script type="text/javascript" id="www-widgetapi-script" src="https://s.ytimg.com/yts/jsbin/www-widgetapi-vflXFLqZz/www-widgetapi.js" async=""></script>
<script src="https://www.youtube.com/player_api"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '315',
      width: '560',
      playerVars : {
            autoplay : 0
        },
      videoId: 'AgPbGevKWWo'
    });
  }
  
  $(window).scroll(function() {
    $("iframe").each( function() {
        if( $(window).scrollTop() > $(this).offset().top - 500 ) {
            $(this).css('opacity',1);
            player.playVideo();
        } else {
            $(this).css('opacity',1);
            player.stopVideo();
        }
    }); 
});
 
</script>
<div id="ytplayer">
<iframe width="560" height="315" src="https://www.youtube.com/embed/AgPbGevKWWo?autoplay=1&cc_load_policy=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
j1rjacob
  • 411
  • 11
  • 27
Pankaj Divgi
  • 66
  • 1
  • 6

3 Answers3

1

Even if the trigger command event is working:: There is no stop command for playing Internet content, you should use the pause command to make sure you've got the previous step right.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
0

One way you could solve this is by putting an event listener on scrolling to detect if the video element is in the viewport. If it is, start playing the video. Else, stop playing the video.

Check this thread : detecting if the element inside the viewport

Ryan Walls
  • 191
  • 1
  • 13
Ali Badr
  • 128
  • 1
  • 10
0

As suggested by the other answers, try maybe :

 $(window).scroll(function() {
    $("iframe").each( function() {
        if($(window).scrollTop() >= $('iframe').offset().top + $(this).innerHeight()) {
            $(this).css('opacity',1);
            player.pauseVideo();
        } else {
            $(this).css('opacity',1);
            player.playVideo();
        }
    }); 
});
Manon
  • 329
  • 1
  • 8