this code block pauses youtube videos on scroll when videos are disappeared from window.
var tag = document.createElement('script'); tag.src = "//www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var youtubePlayers = new Array(); function onYouTubeIframeAPIReady() { var counter = 0; $(".youtube-video").each(function () { counter ; var id = $(this).attr("id"); var onlineId = $(this).attr("data-online-id"); var playerInfo = { id: id, //height: '390', //width: '640', videoId: onlineId }; var curplayer = createPlayer(playerInfo); youtubePlayers[counter] = curplayer; }); } function createPlayer(playerInfo) { return new YT.Player(playerInfo.id, { height: playerInfo.height, width: playerInfo.width, videoId: playerInfo.videoId, }); }$(document).ready(function () { $(window).scroll(function () { $(".youtube-video").each(function () { var isOnScreen = $(this).isOnScreen(); if (!isOnScreen) { var playerId = $(this).attr("id"); $(youtubePlayers).each(function (i, obj) { if (obj != undefined && obj.pauseVideo) { if (obj.a.id == playerId) { obj.pauseVideo(); } } }); } }); });});
Comments