1

I'm attempting to have a YouTube video auto-play when the user scrolls to it and stops when the user scrolls past it. This works fine thanks to this post "JQuery Autoplaying Youtube videos on scroll". Now I want to also do this with window.scroll but it fails. It seems to me that the div containing updated iframe tag is not loaded with youtube APIIframe ready. any one know why. Really appreciate your help?.

Below are my codes

<style type="text/css">
    iframe {
        width: 200px;
        height: 200px;
        margin: 10px 10px 100px 10px;
    }
</style>

<div id="wrap" class="content" style="border:groove">
    <iframe style="margin-top:200px" id="playerA" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/>
    <iframe id="playerB" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/>
    <iframe style="margin-bottom:200px" id="playerC" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
    <div style="height:800px"></div>
</div>

 <script type='text/javascript'>//<![CDATA[

function my_first(){    

    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(){ 
                        //alert('player='+player_id); 
                        //alert('total='+Utils.IsElementInViewport(this.Player.$element[0]) );
                        if( Utils.IsElementInViewport(this.Player.$element[0]) ) this.Play();
                        else this.Pause();
                    },

                    EventHandler: function(){
                        var _this = this;
                        $(window).on('scroll', function(){//alert(player_id)
                            _this.ScrollControl(); 
                        });
                    }
                };
                var Utils = {
                    IsElementInViewport: function(el){
                        if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
                        var rect = el.getBoundingClientRect();

                        return (
                                rect.top >= 100 &&
                                rect.left >= 0 &&
                                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                                rect.bottom <= 400 && 
                                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
                        );
                    }
                };
                return Program.Init();
            };

            $('iframe').each(function(){

                LoadVideo($(this).attr('id'));
            });

}

function yHandler(){

    var wrap=document.getElementById('wrap')  ; 
    var contentHeight = wrap.offsetHeight;//get page content height
    var yOffset = window.pageYOffset;//get vertical scroll position
    var y = yOffset+ window.innerHeight;
    if(y >= contentHeight) {//alert(1234)
        wrap.innerHTML += '<div class="newData"><iframe style="margin-top:0px" id="playerD" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerE" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerF" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><div style="height:500px"></div></div>';              
    }   
}

window.onscroll = function () { 
    $.getScript('//www.youtube.com/player_api');
    yHandler();
    my_first(); 
}

Nobita
  • 330
  • 1
  • 11
jason
  • 15
  • 3

1 Answers1

0

you should be used append not innerHTML.

original:

wrap.innerHTML += '<div class="newData"><iframe style="margin-top:0px" id="playerD" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerE" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerF" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><div style="height:500px"></div></div>';

edit:

$(wrap).append( '<div class="newData"><iframe style="margin-top:0px" id="playerD" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerE" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><iframe style="margin-top:0px" id="playerF" frameborder="0" title="YouTube video player" type="text/html" src="https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe><br/><div style="height:500px"></div></div>' ); 

reference: jquery .html() vs .append()

hope it helps

UPDATE

create iframe with different id

function createVideo( $element, url ) {
    $element.append( '<iframe style="margin-top:0px" id="player' + $( 'iframe' ).length + 1 + '" frameborder="0" title="YouTube video player" type="text/html" src="' + url + '"></iframe><br/>');
}
createVideo( $(wrap), "https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" );
createVideo( $(wrap), "https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" );
createVideo( $(wrap), "https://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" );
$(wrap).append( '<div style="height:500px"></div>');
  • Thanks so much. However, it seems to me that the problem is still there. That is the onscroll is working, new div is appended but the onYoutubeAPIIframeReady is still not loaded for the new div when I scroll to the appended video.Could it be something wrong with my NewPlayer:function() part – jason Nov 22 '17 at 11:16
  • you should be used different id when creating new element – Hsueh Ming-Fang Nov 23 '17 at 09:34
  • Thanks Ming-Fang for clean up and reorganise my code by using the createVideo function. It looks much better now. Still, i do not quite understanding what you said by using different id when creating new element. How do I apply it here? Much appreciate. I have just attempted to include the below function into the window.onscroll , but it seems it only works for once scrolling . If I scroll it twice , nothing changes??? – jason Nov 23 '17 at 12:04
  • function myPluginLoadEvent(func) { var oldOnLoad = window.onload; if (typeof window.onload != 'function') { window.onload = func } else { window.onload = function () { oldOnLoad(); func(); } } } myPluginLoadEvent(my_first); – jason Nov 23 '17 at 12:12
  • you can try to include the below function into the yHandler, I'd create a example https://jsbin.com/sigesujixa/edit?html,output than it's work. – Hsueh Ming-Fang Nov 24 '17 at 02:51
  • Thank you so so much. It really works. You are such a great saver. Don't know what to say. It took me 2 weeks and i could not go nowhere until now. Again, thanks so much. – jason Nov 24 '17 at 07:39