F0xcr4f7 F0xcr4f7 - 19 days ago 15
jQuery Question

JQuery Autoplaying Youtube videos on scroll

Issue: I'm attempting to have a YouTube video auto-play when the user scrolls to it and stops when the user scrolls past it.

Constraints: New to JavaScript web development.

Tried: Going off of https://jsfiddle.net/kmsdev/gsfkL6xL/ I copy pasted line for line just to get it to work. I'm familiar with C++ and Java so I can at least read the main points of the code. It seems that I have the code correct but I might not be calling it correctly within my HTML5?

Hero Section:

<section class="video_background">
<div class="video_foreground">
<iframe id="playerA" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</div>
</section>


JS Section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/scroll.js"></script>


JS:

$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});


I have this on top of https://jsfiddle.net/kmsdev/gsfkL6xL/ but that shouldn't matter.

Answer

Here is a working example, this includes all css/js in one. I can't see what you did with your version of the PlayYTVideos source but you may have forgotten to do window.onload.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
    <style type="text/css">
        iframe {
            width: 200px;
            height: 200px;
            margin: 500px 0;
        }
    </style>
    
    <script type='text/javascript'>//<![CDATA[
    window.onload=function(){
        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 = {
                /** @author http://stackoverflow.com/a/7557433/1684970 */
                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');
        LoadVideo('playerB');
        LoadVideo('playerC');
    }//]]>

    </script>
    
</head>
<body>
<iframe id="playerA" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
<iframe id="playerB" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
<iframe id="playerC" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</body>
</html>