0

I mean to say that the video should not be playing when the page is loaded. It should play when the video player comes in the focus of the window screen and it should pause when it is not visible on the screen using the scroll function. I am not expecting to play videos on separate tabs.

        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

            </head> 
            <body>
                <p>
                    This is some text
                </p>


                <div style="margin-top:1000px;margin-bottom:1000px;">
                <iframe width="445" height="245" src="https://www.youtube.com/embed/LA5XtlyVILo?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
               </div>

                <script type="text/javascript">
                   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 if(visible < fraction) {
                          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();

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

                    function pauseVideo() {
                      player.pauseVideo();
                    }
                </script>
            </body>
        </html>

3 Answers3

1

Update based on Posters Feedback

After searching around on stackoverflow to expand on my own solution to the problem, I found the answer to your question in another stackoverflow question.

Here's a fiddle slightly modified fiddle based on the original post

 /*Credit to original author http://stackoverflow.com/a/7557433/1684970 */

var LoadVideo = function(player_id) {

var Program = {

  Init: function() {
    this.NewPlayer();
    this.EventHandler();
  },

  NewPlayer: function() {
    var _this = this;
    this.Player = new YT.Player(player_id, {});
    _this.Player.$element = $('#' + player_id);
  },

  Play: function() {
    if (this.Player.getPlayerState() === 1) return;
    this.Player.playVideo();
  },

  Pause: function() {
    if (this.Player.getPlayerState() === 2) return;
    this.Player.pauseVideo();
  },

  ScrollControl: function() {
    if (Utils.IsElementInViewport(this.Player.$element[0])) this.Play();
    else this.Pause();
  },

  EventHandler: function() {
    var _this = this;
    $(window).on('scroll', function() {
      _this.ScrollControl();
    });
  }

};

var Utils = {
  IsElementInViewport: function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

};

return Program.Init();

};

LoadVideo('playerA');

Original Answer

Since you haven't specified if the video is in a iframe or anything, I will assume it's just embedded and offers the user play/pause/open in youtube options.

The first part is detecting if the element is currently in the viewport, and therefore visible. and then the click event if visible/not-visible.

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();

    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // The element is visible, trigger play click event
        $("#element").playVideo()
    }
    else {
        // The element is not visible, trigger pause click event
        $("#element").pauseVideo()
    }
});
Tinus Wagner
  • 895
  • 1
  • 7
  • 15
0

You can fire the pause event for the player by watching on the scroll event for the page as

$(window).scroll(function() {
    if($(window).scrollTop() > height) { //height is the pixels by which if you scroll the player gets hidden
        player.pauseVideo();  //player is the YouTube player object you created
    }
    else
        player.playVideo(); //the player is visible.
});
Saksham
  • 8,110
  • 6
  • 35
  • 63
0

Correct Code for this question.

        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <script src="//www.youtube.com/player_api"></script>
            </head> 
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
               </div>
                <div id="player"></div>
                <script type="text/javascript">
                    src="//www.youtube.com/player_api"
                    var player;
                    function onYouTubeIframeAPIReady() {
                      player = new YT.Player('player', {
                        height: '245',
                        width: '445',
                        videoId: 'FSfz0NxzN80',
                        rel:'0'             
                      });
                    } 

                   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) {           
                      player.playVideo();
                        } 
                        else if(visible < fraction) {
                      player.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();

                </script>
            </body>
        </html>