otti242
9/25/2018 - 2:33 PM

PlayVideoVisible.js

/* esLint */
/*
  global
    jQuery
*/
(function ($) {
    'use strict';

    function Youtube() {



        
        this.init = function () {
            var isIE11 = !!navigator.userAgent.match(/Trident.*rv\:11\./);
            var touch = isTouchDevice();
            var mobile = isMobileDevice();
            var element = $('.youtube');
            var players = new Array();
            
            window.onYouTubeIframeAPIReady = function () {
                //console.log('after ready'); 
            };

            if (!Element.prototype.replaceWith)
                Element.prototype.replaceWith = ReplaceWith;
            if (!CharacterData.prototype.replaceWith)
                CharacterData.prototype.replaceWith = ReplaceWith;
            if (!DocumentType.prototype.replaceWith)
                CharacterData.prototype.replaceWith = ReplaceWith;

            if (mobile === false && touch === false && isIE11 === false) {
                
                window.iframeIsReady = function iframeIsReady(callback) {
                    // Listen for Gobal YT player callback
                    if (typeof YT === 'undefined' && typeof window.loadingPlayer === 'undefined') {
                      // Prevents Ready Event from being called twice
                      window.loadingPlayer = true;
              
                      // Creates deferred so, other players know when to wait.
                      window.dfd = $.Deferred();
                      window.onYouTubeIframeAPIReady = function() {
                        window.onYouTubeIframeAPIReady = null;
                        window.dfd.resolve( "done" );
                        callback();
                      };
                    } else if (typeof YT === 'object')  {
                      if(typeof YT.Player !== 'undefined'){
                        callback();
                      } else{
                        window.dfd = $.Deferred();
                        window.onYouTubeIframeAPIReady = function() {
                          window.onYouTubeIframeAPIReady = null;
                          window.dfd.resolve( "done" );
                          callback();
                        };
                      }
                      
                    } else {
                      window.dfd.done(function( name ) {
                        callback();
                      });
                    }
                  };

                var checkYT = setInterval(function () {
                    if(window.onYouTubeIframeAPIReady){
                        //...setup video here using YT.Player()
                        element.each(function (i) {
                            if ($(this).data('video-autoplay') === 0) {
                                mobileVideo($(this));
                               return;
                            }
                            
                            var playerNumber = players.length;
                            var getYtID = $(this).data('video-id');
                            var getHeight = $(this).data('video-height');
                            var parent = $(this).parent('.youtube-element');
                            var source = "//img.youtube.com/vi/" + getYtID + "/hqdefault.jpg";
                            var image = new Image();
                            image.src = source;
    
                            image.onload = function () {
                                parent.append(image);
                            };
                            if (!getHeight || getHeight % 1 !== 0 || getHeight < 200) {
                                getHeight = "590";
                            }
    
                            $(this).attr('id', 'player' + i);

                            players.push(
                                new YT.Player('player' + i, {
                                    height: getHeight,
                                    width: '100%',
                                    videoId: getYtID,
                                    playerVars: { allowfullscreen: '0', modestbranding: '0', controls: '1', rel: '0', showinfo: '0', color: 'red', loop: '0', mute: '1' },
                                    events: {
                                        'onReady': onYouTubeIframeAPIReady,
                                        'onStateChange': onPlayerStateChange
                                    }
                            }));


                            var thatPlayer = players[playerNumber];
                            var thatElement = $(thatPlayer.a);
                                        
                            $(window).on('ecx.scrollDebounce', function () {
    
                                if (isElementInViewport(thatElement)) {
                                    thatPlayer.playVideo();
                                    thatElement.removeClass('show');
                                }
    
                                else {
                                    thatPlayer.pauseVideo();
                                    thatElement.addClass('show');
                                }
                            });
                        });
                
                        clearInterval(checkYT);
                    }
                }, 100);


                insertYTScript();
                
            } else {
                element.each(function () {
                    mobileVideo($(this));
                });
            }
            
        };

        function insertYTScript() {
            //Inject YouTube API script
            var tag = document.createElement('script');
            tag.src = "//www.youtube.com/player_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        }

        function isTouchDevice() {
            try {
                document.createEvent("TouchEvent");
                return true;
            } catch (e) {
                return false;
            }
        }

        // You can polyfill the replaceWith() method in Internet Explorer 6 and higher with the following code
        // https://developer.mozilla.org/de/docs/Web/API/ChildNode/replaceWith
        function ReplaceWith(Ele) {
            'use-strict'; // For safari, and IE > 10
            var parent = this.parentNode,
                i = arguments.length,
                firstIsNode = +(parent && typeof Ele === 'object');
            if (!parent) return;

            while (i-- > firstIsNode) {
                if (parent && typeof arguments[i] !== 'object') {
                    arguments[i] = document.createTextNode(arguments[i]);
                } if (!parent && arguments[i].parentNode) {
                    arguments[i].parentNode.removeChild(arguments[i]);
                    continue;
                }
                parent.insertBefore(this.previousSibling, arguments[i]);
            }
            if (firstIsNode) parent.replaceChild(Ele, this);
        }


        function mobileVideo(youtube) {
            var that = youtube;
            var getYtID = youtube.data('video-id');
            var iframe = document.createElement("iframe");
            iframe.setAttribute("frameborder", "0");
            iframe.setAttribute("allowfullscreen", "");
            iframe.setAttribute("src", "https://www.youtube.com/embed/" + getYtID + "?rel=0&showinfo=0&autoplay=0&enablejsapi=1");
            that[0].innerHTML = "";
            that[0].replaceWith(iframe);
        }

        // Only for debugging, uncommend console.logs
        function onPlayerStateChange(event) {
            if (event.data === YT.PlayerState.PLAYING) {
                //console.log('video is playing');
            }

            if (event.data === YT.PlayerState.PAUSED) {
                //console.log('video is paused');
            }

            if (event.data === YT.PlayerState.ENDED) {
                //console.log('video has ended');
            }
        }

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

        function isMobileDevice() {
            var ua = navigator.userAgent;
            var mobile = false;
            if (ua.match(/(iPhone|iPod|iPad|BlackBerry|Android)/)) {
                mobile = true;
            }
            return mobile;
        }
    }


    window.Youtube = new Youtube();
})(jQuery);