Hi I used iframe api to create yt movie player.I encountered problem on Google chrome for mobile. To start movie i used playVideo() function. I see that movie is loading but after that i see nothing more than black yt player with no sound. I tested it on my pc computer, Google Chrome for mobile, my colleague iPhone 4s and even on my HTC Wildfire S with native browser. Everything was fine.
Example
To create movie:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1, player2, player3;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('ytapiplayer1', {
height: '390',
width: '640',
videoId: 'Vhik235dWLk',
});
player2 = new YT.Player('ytapiplayer2', {
height: '390',
width: '640',
videoId: 'p_Y5WjjVb9I',
});
player3 = new YT.Player('ytapiplayer3', {
height: '390',
width: '640',
videoId: '6HOo7_NNHu4',
});
}
HTML:
<div id="owl-example" class="owl-carousel">
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/Vhik235dWLk/0.jpg)">
<div id="ytapiplayer1"></div>
</div>
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/p_Y5WjjVb9I/0.jpg)">
<div id="ytapiplayer2"></div>
</div>
<div class="video-container" style="background-image: url(http://img.youtube.com/vi/6HOo7_NNHu4/0.jpg)">
<div id="ytapiplayer3"></div>
</div>
</div>
CSS:
.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px; height: 0; overflow: hidden;
background-repeat: no-repeat;
background-position: center center;
background-size: 100%;
}
.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
JS to start owl carousel and play, stop movie
$(document).ready(function() {
$("#owl-example").owlCarousel({
singleItem : true,
afterMove: function(){
$('.video-container').css('background-position', 'center')
$('iframe').hide();
player1.stopVideo();
player2.stopVideo();
player3.stopVideo();
}
});
$('body').on('click', '.video-container', function(){
var owl = $(".owl-carousel").data('owlCarousel');
console.log(owl.currentSlide)
if (owl.currentSlide == 0){
player1.playVideo()
}
if (owl.currentSlide == 1){
player2.playVideo()
}
if (owl.currentSlide == 2){
player3.playVideo()
}
$(this).css('background-position', '-1000px -1000px');
$(this).find('iframe').show()
});
});
Related
I have a few youtube videos embedded in a couple of iframes, and would like to start stop all the videos at once, using only one button. I've tried a few different methods, but just couldn't get it right.
Here is what I got.
main.html:
<!DOCTYPE html>
<html>
<head>
<title>YT Mosaic</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="container">
<div class="mosaic">
<iframe id="if1" src="https://www.youtube.com/embed/5mL-OkdM7Tc?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- TRT -->
<iframe id="if2" src="https://www.youtube.com/embed/9Auq9mYxFEE?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- SKY -->
<iframe id="if3" src="https://www.youtube.com/embed/VBTdNwm5CDY?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Global News -->
<iframe id="if4" src="https://www.youtube.com/embed/ntmPIzlkcJk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Euronews -->
<iframe id="if5" src="https://www.youtube.com/embed/GE_SfNVNyqk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- DW -->
<iframe id="if6" src="https://www.youtube.com/embed/h3MuIUNCCzI?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- F24 -->
</div>
<button onclick="iframe1play(); return false;">⏯️</button>
<button onclick="stop();">⏹</button>
<button onclick="playAll();">▶▶ Play All</button>
</div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var ifa = []; // array of iframe id's
var ifos = []; // array of iframe YT objects for use elsewhere
// For each iframe you find, add its ID to the ifa array
var iframes = document.querySelectorAll("div.mosaic iframe");
iframes.forEach(function(iframe) {
ifa.push(iframe.id);
});
console.log('[LOG] iframe array:', ifa)
// Array(6) [ "if1", "if2", "if3", "if4", "if5", "if6" ]
// Once the YouTube API is ready, for each iframeId in your array,
// create a new YT player and give it the onReady event.
function onYouTubeIframeAPIReady() {
ifa.forEach(function(iframeId) {
var player = new YT.Player(iframeId, {
events: {
'onReady': onPlayerReady,
}
});
});
}
function onPlayerReady(event) {
var ifo = event.target;
ifos.push(ifo); // Push current iframe object to ifo array
ifos.forEach(function(j) {
j.setVolume(30);
j.playVideo();
j.unMute();
});
}
var player;
// WARNING this need to be commented out as it interferes with the other version.
function onYouTubeIframeAPIReady() {
player = new YT.Player('if1', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000); // wait 6 s. before stopping player
done = true;
}
}
function catchError(event) {
if (event.data == 2) console.log("[LOG] Error: The request contains an invalid parameter value.");
if (event.data == 5) console.log("[LOG] Error: content cannot be played in an HTML5 player.");
if (event.data == 100) console.log("[LOG] Error: Video doesn't exists (or has been removed)!");
if (event.data == 101) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
if (event.data == 150) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
// This should never happen!
console.log("Error:\n", event);
}
// This was a test, not working, trying to use:
// onload="p1=new YT.Player(this);">
function playAll() {
var ifs = [p1,p2,p3,p4,p5,p6];
for(var i=0; i<ifs.length; i++) {
console.log("Try to Play: ", toString(ifs[i]));
ifs[i].playVideo();
}
}
function play() {
//player.unMute();
player.playVideo();
//show_video_url();
}
function pause() { player.pauseVideo(); }
function stop() { player.stopVideo(); }
function stopVideo() { player.stopVideo(); }
function mute() { player.unMute(); }
function iframe1play() {
if (player.getPlayerState() == YT.PlayerState.PLAYING) {
player.pauseVideo();
document.getElementById("if1").style.opacity = "0.7";
} else {
player.playVideo();
document.getElementById("if1").style.opacity = "1";
}
}
</script>
</body>
<footer>FTSE</footer>
</html>
and here is the CSS file main.css:
body {
background-color: #404040;
color: lightgrey;
margin: 0;
padding: 1em;
/*height: 100vh;*/
box-sizing: border-box;
}
.container {
max-width: 1100px;
/* width: 100%;*/
border: 1px solid black;
padding: 10px;
}
.mosaic {
display: grid;
/* Setup a 2x3 frame: */
/* fr is a fractional unit and 1fr is for 1 part of the available space */
grid-template-columns: 1fr 1fr;
grid-template-rows: 50% 50% 50%;
/*grid-template-rows: 1fr 1fr 1fr;*/
max-width: 1100px; /* 100% */
max-height: 100%; /* 100% */
/*aspect-ratio: 16/9;*/ /* 16/9 */
/* margin: auto; */ /* auto */
margin-bottom: 1em; /* 1em */
/*padding: 2em; */
gap: 5px; /* 1em */
}
iframe {
/* iframe width="560" height="315" */
display: block;
width: 100%;
height: 100%;
aspect-ratio: 16/9; /* */
/*min-width: 350px;*/ /* 350px */
/*min-height: 200px;*/ /* 200px */
background: gray; /* yellow */
border: 1px solid black; /* border: solid red */
margin: 0px; /* */
}
How can I use the iframe id= tag to start all iframe videos using one button?
preferably using JS without additional libraries, such as jQuery.
JSfiddle code
You can use Youtube's IFrame Player API. They have a great documentation here https://developers.google.com/youtube/iframe_api_reference
You can basically control all youtube embed videos by generating it through their API.
A working sample would be down below:
<body>
<div id="container">
<div id="player-5mL-OkdM7Tc"></div> <!-- TRT -->
<div id="player-9Auq9mYxFEE"></div> <!-- SKY -->
<div id="player-VBTdNwm5CDY"></div> <!-- Global News -->
<div id="player-ntmPIzlkcJk"></div> <!-- Euronews -->
<div id="player-GE_SfNVNyqk"></div> <!-- DW -->
<div id="player-h3MuIUNCCzI"></div> <!-- F24 -->
</div>
<button onclick="play()">
Play All
</button>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="main.js" async defer></script>
</body>
let playersObjs = [];
window.onYouTubeIframeAPIReady = () => {
const playerContainers = document.querySelectorAll('div[id^="player"]');
playerContainers.forEach((container) => {
const videoId = container.id.slice(7);
playersObjs.push(new YT.Player(container.id, {
height: '200',
width: '100',
videoId,
playerVars: {
'playsinline': 1
}
}))
})
}
const play = () => {
playersObjs.forEach((player) => {
player.playVideo();
})
}
I have created an iframe by taking advantage of YouTube's API.
On page load, the ambient video is set to autoplay with no sound. However, on top of the div which contains the iframe, I have a button.
On this button click, I want the video to reset (start from the beginning) with the YouTube controls and sound on - similar to the one in the hero here: https://www.hugeinc.com/work.
Wondering how I would go about this? Would it involve creating another iframe?
Not looking to do this as a modal pop-up
Code:
// Load IFrame Player API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Creating iframe
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'jagIsKF8oVA',
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1,
'rel': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// Calls function
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
// if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
// done = true;
// }
}
function stopVideo() {
// player.stopVideo();
}
<!-- THIS IS IN home.php-->
<button>Click me</button>
<!-- THIS IS IN hero.php -->
<section id="videoHero" class="hero hero--video">
<div class="hero__container--teaser">
<!-- Where the iframe is stored-->
<div id="player"></div>
</div>
</section>
Not looking to do this as a modal pop-up. Similar to the functionality here: https://www.hugeinc.com/work (play button on hero is clicked, video resets and plays from the start with controls at the bottom).
I used another iframe because there is no method to change the controls display you may check https://developers.google.com/youtube/iframe_api_reference for more information or you can do console.log(player) and ckeck all the methods.
I used
contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
to stop the iframe and
contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
to restart it also for this two line of code to work I added &enablejsapi=1 to the iframe src
also I used the YouTube Player API for the muted video so that it will loop whiteout refresh (in case of not using the YouTube Player API for the video to loop you need to add to the src of the iframe playlist=videoId&loop=1 and this will make the iframe refresh when the video end)
I haven't added showinfo=0 to the muted video because it is deprecated and will be ignored after September 25, 2018.
you may check https://developers.google.com/youtube/player_parameters#showinfo for more info
Lastly the snippet doesn't work . you need to make local html file or delete sandbox from the sinppet iframe then click on Run code snippet a second time
var modalTeaser = document.getElementById('hero__container--teaser');
var btn = document.getElementById("myBtn");
var iframe = document.getElementById("iframe");
var span = document.getElementsByClassName("close")[0];
var videoId = '88xPxULx-II';
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('iframe', {
videoId: videoId,
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data === YT.PlayerState.ENDED) {
player.playVideo();
}
}
var video = document.createElement('iframe');
video.className = "ply";
modalTeaser.prepend(video);
video.style.display = 'none';
video.src = "https://www.youtube.com/embed/"+videoId+"?enablejsapi=1";
video.setAttribute('frameborder', "0");
btn.onclick = function() {
iframe.style.display = "none";
video.style.display = "block";
btn.style.display = "none";
span.style.display = "block";
video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
}
span.onclick = function() {
iframe.style.display = "block";
video.style.display = "none";
btn.style.display = "block";
span.style.display = "none";
video.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
}
body {
margin: 0;
}
.close{
z-index: 10;
position: relative;
display: none;
}
.ply{
z-index: 2 !important;
}
#videoHero {
position: relative;
padding-bottom: calc((544 / 1280) * 100%);
background-color: rgba(255, 0, 0, .1)
}
.hero__container--teaser {
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
.modal{
width: 80%;
height: 80%;
background-color: black;
}
/* Having the following on the iframe moves the iframe out of the div (and visual). Not having them puts
the iframe in the div, but not full width not height of #videoHero*/
#player,
iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -10;
}
#myBtn {
position: absolute;
top: 80px;
left: 300px;
z-index: 10;
width: 100px;
height: 100px;
background-color: red;
}
.modal {
display: none;
position: fixed;
z-index: 122;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.modal-content {
z-index: 400;
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
<section id="videoHero" class="hero hero--video">
<button type="button" class="close" data-dismiss="modal" aria- label="Close">
<span aria-hidden="true">×</span>
</button>
<div id="hero__container--teaser" class="hero__container--teaser">
<!-- #player is where the iframe is-->
<div id="iframe" ></div>
</div>
<button id="myBtn">Start video</button>
</section>
I'm experimenting with embedding youtube videos, and am hoping to create a video that users can't interact with. I've managed to remove all the ui stuff, but can't seem to prevent clicking. I stumbled upon a website that is doing exactly what I want to do: on the bottom right, there is a youtube video with an apparent overlay that prevents clicking; it seems simple enough but I can't figure it out! Any advice would much appreciated. Here's my code so far:
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'BalUcQpYN6k',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>
You can simply add this to your css.
#player {pointer-events: none;}
#player {pointer-events: none;}
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'iRkCIuY2pHc',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>
I dont know how I ended up back here a year later but out of curious I went and looked up the OP's link and pointer-events: none is exactly what they are using, as shown below.
.player-container > .modal-inner-container > #player, .player-container > .modal-inner-container #html5-player, .lyrics-container > .modal-inner-container > #player, .lyrics-container > .modal-inner-container #html5-player {
pointer-events: none;
width: 100%;
height: 100%;
background-color: #000;
Update HTML with a bit more:
<div id="playArea">
<div id="player"></div>
<div class="yt-overlay"></div>
</div>
And add this CSS:
.yt-overlay, .#playArea > .yt-overlay {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1000;
}
Place a block element before the player. (#shield)
Next wrap both #shield and #player in a block element. (#main)
The important part is #main is position:relative and it's children elements are position:absolute with the overlay (#shield) having a higher z-index than the #player.
The rest of the Snippet should be self-explanatory.
SNIPPET
#main {
position: relative;
width: 400px;
height: 250px;
z-index: -1;
}
#shield {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
pointer-events: none;
cursor: not-allowed;
background: transparent;
}
#player {
position: absolute;
}
<!DOCTYPE html>
<html>
<body>
<main id='main'>
<section id='shield'></section>
<div id="player"></div>
</main>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var start = 30;
var end = 35;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '250',
width: '400',
videoId: 'BalUcQpYN6k',
playerVars: {
'autoplay': 1,
'controls': 0,
'disablekb': 1,
'start': start,
'end': end,
'fs': 0,
'iv_load_policy': 3,
'loop': 0,
'modestbranding': 1,
'showinfo': 0,
'rel': 0
}
});
}
</script>
</body>
</html>
I want to play a youtube embed video and pause it on a cerain time, beside show an hidden ad and start the video after the ad has been clicked. could anyone tell me where is the error?
var time_cok = 7.25;
var adhac_mod = 10;
var adhac_tm_min = 20;
var adhac_tm_max = 25;
function setCookie(e,t,a){var r=new Date;r.setTime(r.getTime()+24*a*60*60*1e3);var n="expires="+r.toUTCString();document.cookie=e+"="+t+"; "+n+"; path=/"}function getCookie(e){for(var t=e+"=",a=document.cookie.split(";"),r=0;r<a.length;r++){for(var n=a[r];" "==n.charAt(0);)n=n.substring(1);if(0==n.indexOf(t))return n.substring(t.length,n.length)}return""}function randomIntFromInterval(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function setAdHac(){var e=getCookie("adhac");if(!e){var t={width:"100%",height:"100%",opacity:"0",position:"absolute","z-index":"9998"},a={"minwidth":"400px","max-width":"700px","min-height":"280px",margin:"110px 0 auto",overflow:"hidden","text-align":"center",visibility:"hidden","zindex":"9999"};document.getElementById("ytplayer").innerHTML+="<div></div>",jQuery("#below-ad").css(t),jQuery("#below-ad > div").css(a),jQuery("#belowad").prependTo("#ytplayer"),setCookie("adhac",1,time_cok)}}function onYouTubeIframeAPIReady(){player=new YT.Player("player",{events:{onStateChange:onPlayerStateChange}})}function onPlayerStateChange(e){if(e.data==YT.PlayerState.PLAYING){var t=1e3*randomIntFromInterval(adhac_tm_min,adhac_tm_max);if(2==adhac_mod){var a=player.getDuration(),r=0;60>=a?r=randomIntFromInterval(35,50):a>60&&100>=a?r=randomIntFromInterval(30,40):a>100&&160>=a?r=randomIntFromInterval(20,25):a>160&&(r=randomIntFromInterval(10,15));var n=a*(r/100),t=1e3*Math.round(n)}setTimeout(function(){setAdHac()},t)}}var ytplayer=document.getElementById("ytplayer");if(ytplayer)if(0==adhac_mod)setAdHac();else{var tag=document.createElement("script");tag.src="https://www.youtube.com/iframe_api";var firstScriptTag=document.getElementsByTagName("script")[0];firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);var player}
Here is the HTML code
<!--Youtube Video-->
<div id="ytplayer" style="position: relative; display: inline-block;"><iframe id="player"title="YouTube video player"src="https://www.youtube.com/embed/5PGEWejcmNU?enablejsapi=1&showinfo=0" width="560"
height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>
<!--AD-->
<div id="below-ad" style="width: 100%; position: relative;"><div style= min-width: 400px; max-width: 700px; min-height: 280px; margin: 0 auto; overflow: hidden; text-align: center; visibility: hidden; zindex:9999;">
AD SCRIPT HERE
</div>
I have 11 Youtube videos in a page i wnat to track all of them using Youtube Api and Google Analytics below is what i have tried please help me how to debug using the Google Analytics Debugger and where i have gone wrong
I am using New analytics.js
HTML
<div style="margin-bottom: 24px;">
<iframe id="video01" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/xxx?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video02" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/yyy?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video03" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/zzz?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video04" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/eee?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video05" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/rrr?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video06" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/www?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video07" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/qqq?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video08" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/bbb?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video09" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/lll?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video10" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/ooo?enablejsapi=1" frameborder="0"></iframe>
<iframe id="video11" style="margin-bottom: 16px; margin-right: 16px;" class="etib" width="340" height="220" src="https://www.youtube.com/embed/kkk?enablejsapi=1" frameborder="0"></iframe>
</div>
Java Script
$(function () {
try {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var video01, video02, video03, video04, video05
, video06, video07, video08, video09, video10, video11,
playerInfoList =
[
{ id: 'video01', height: '390', width: '640', videoId: 'ml_BgIm3FzY' }, { id: 'video02', height: '390', width: '640', videoId: 'hV__30BVW8U' },
{ id: 'video03', height: '390', width: '640', videoId: 'A9H93F-8WQk' }, { id: 'video04', height: '390', width: '640', videoId: 'C9N2Chg6E7A' },
{ id: 'video05', height: '390', width: '640', videoId: '-J07hSBRfL8' }, { id: 'video06', height: '390', width: '640', videoId: 'Faor8xaj5RI' },
{ id: 'video07', height: '390', width: '640', videoId: 'R2qR5atJQ6o' }, { id: 'video08', height: '390', width: '640', videoId: 'n-2q3cu5JNA' },
{ id: 'video09', height: '390', width: '640', videoId: 'g963TyA8bgc' }, { id: 'video10', height: '390', width: '640', videoId: '5p4PodfYQEQ' },
{ id: 'video11', height: '390', width: '640', videoId: 'Uba6pRWWr6o' }];
function onYouTubeIframeAPIReady() {
if (typeof playerInfoList === 'undefined')
return;
$.each(playerInfoList, function (index, playerInfo) {
var video = playerInfo.id;
video = createPlayer(playerInfo)
});
function createPlayer(playerInfo) {
return new YT.Player(playerInfo.id, {
height: playerInfo.height,
width: playerInfo.width,
videoId: playerInfo.videoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var pauseFlag = false;
function onPlayerStateChange(event) {
// track when user clicks to Play
if (event.data == YT.PlayerState.PLAYING) {
_gaq.push(['_trackEvent', 'Videos', 'Play', 'Test Video']);
pauseFlag = true;
}
// track when user clicks to Pause
if (event.data == YT.PlayerState.PAUSED && pauseFlag) {
_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Test Video']);
pauseFlag = false;
}
// track when video ends
if (event.data == YT.PlayerState.ENDED) {
_gaq.push(['_trackEvent', 'Videos', 'Finished', 'Test Video']);
}
}
}
catch (Exception) { }
});
I am seeing this in console section
I just shared this with another similar question, so while it uses jQuery, hopefully it can shed some light on your issue. I've altered it to use the older _gaq.push() method for Google Analytics to match your question.
Here's a script I came up with that works with any number of embedded Youtube videos on a page. I apologize that this uses jQuery, but the idea is there: loop through each Youtube embed and assign it as a player based on its index. I'm also pretty certain this could be optimized a bit too.
It uses the class youtubeplayer to loop through each embed.
<script>
var players = {};
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(e){
jQuery('iframe.youtubeplayer').each(function(i){
var youtubeiframeClass = jQuery(this).attr('id');
players[youtubeiframeClass] = new YT.Player(youtubeiframeClass, {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
}
var pauseFlag = false;
function onPlayerReady(e){
//Player ready functions would go here
}
function onPlayerStateChange(e){
var videoTitle = e['target']['B']['videoData']['title'];
if ( e.data == YT.PlayerState.PLAYING ){
_gaq.push(['_trackEvent', 'Videos', 'Play', videoTitle]);
pauseFlag = true;
}
if ( e.data == YT.PlayerState.ENDED ){
_gaq.push(['_trackEvent', 'Videos', 'Finished', videoTitle]);
} else if ( e.data == YT.PlayerState.PAUSED && pauseFlag ){
_gaq.push(['_trackEvent', 'Videos', 'Pause', videoTitle]);
pauseFlag = false;
}
}
</script>
Hope this at least gets you headed in the right direction!