I am currently working on a page with a slider with various iframe youtube embeds.
I am trying to get my JS to pause the video when you hit the "next" button on the slider. I think I've got everything set up according to the api.. but it doesn't seem to pause the videos when you click the slider button.
<script type="text/javascript">
// https://developers.google.com/youtube/iframe_api_reference
// global variable for the player
var player;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
// bind events
var pauseButtonRight = document.getElementByID("pause-right");
pauseButtonRight.addEventListener("click", function() {
player.pauseVideo();
});
var pauseButtonLeft = document.getElementByID("pause-left");
pauseButtonLeft.addEventListener("click", function() {
player.pauseVideo();
});
}
// 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);
</script>
my iframes:
<iframe src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>
Any direction would be appreciated.
A few things :
this is document.getElementById not document.getElementByID
you've instanciated a Youtube player with id 'video' but your iframe don't have any id :
<iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>
use onYouTubeIframeAPIReady instead of onYouTubePlayerAPIReady
You will have something like :
var player;
function onYouTubeIframeAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
var pauseButtonRight = document.getElementById("pause");
pauseButtonRight.addEventListener("click", function() {
player.pauseVideo();
});
var pauseButtonLeft = document.getElementById("play");
pauseButtonLeft.addEventListener("click", function() {
player.playVideo();
});
}
// 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);
with :
<iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>
<input id="pause" type="submit" value="pause" />
<input id="play" type="submit" value="play" />
Check this fiddle
Check Youtube iframe API reference
Related
I need to embed multiple YouTube videos on a website. For each video, I need to set up an external element (such as a paragraph, image, div, etc) that can trigger the YouTube video to play, and a separate element that will trigger the YouTube video to pause.
I have some Javascript code that I can use to play/pause one embedded YouTube video. However, if I attempt to create play/pause buttons for more than one YouTube video on the same page, only the buttons for the last YouTube video will work.
To demonstrate the issue, I created two JS Fiddles. The first Fiddle shows how it works when there is only one YouTube video on the page.
The second Fiddle shows what happens when I try to create buttons for more than one YouTube video on the same page. As you'll see, only the buttons for the last YouTube video work.
Any suggestions would be greatly appreciated. I've included the JS Fiddle links (and the accompanying code) below. Thank you!
JS Fiddle #1 (1 video)
https://jsfiddle.net/IngeniousSolutions/gtfprovc/14/
JS Fiddle #2 (2 videos)
https://jsfiddle.net/IngeniousSolutions/4m95ogfd/2/
CODE FOR JS FIDDLE #1
HTML Code for JS Fiddle #1
<p>VIDEO #1</p>
<div class="fullwidth">
<button id="play-button">PLAY</button>
<button id="pause-button">PAUSE</button>
<button id="stop-button">STOP</button>
</div>
<div class="fullwidth">
<iframe id="video" src="https://www.youtube.com/embed/aIXOyOLkb24?enablejsapi=1&html5=1" frameborder="0"
allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
CSS Code for JS Fiddle #1:
.fullwidth {width: 100%;}
Javascript Code for JS Fiddle #1
// global variable for the player
var player;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function () {
player.playVideo();
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function () {
player.pauseVideo();
});
var stopButton = document.getElementById("stop-button");
stopButton.addEventListener("click", function () {
player.stopVideo();
});
}
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
CODE FOR JS FIDDLE #2
HTML Code for JS Fiddle #2
<p>VIDEO #1</p>
<div class="fullwidth">
<button id="play-button">PLAY</button>
<button id="pause-button">PAUSE</button>
<button id="stop-button">STOP</button>
</div>
<div class="fullwidth">
<iframe id="video" src="https://www.youtube.com/embed/aIXOyOLkb24?enablejsapi=1&html5=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<p>VIDEO #2</p>
<div class="fullwidth">
<button id="play-button2">PLAY</button>
<button id="pause-button2">PAUSE</button>
<button id="stop-button2">STOP</button>
</div>
<div class="fullwidth">
<iframe id="video2" src="https://www.youtube.com/embed/4zTCd-k--7A?enablejsapi=1&html5=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
CSS Code for JS Fiddle #2:
.fullwidth {width: 100%;}
Javascript Code for JS Fiddle #2
// global variable for the player
var player;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function () {
player.playVideo();
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function () {
player.pauseVideo();
});
var stopButton = document.getElementById("stop-button");
stopButton.addEventListener("click", function () {
player.stopVideo();
});
}
// Javascript for second video
// global variable for the player
var player2;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player2 = new YT.Player('video2', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
var playButton2 = document.getElementById("play-button2");
playButton2.addEventListener("click", function () {
player2.playVideo();
});
var pauseButton2 = document.getElementById("pause-button2");
pauseButton2.addEventListener("click", function () {
player2.pauseVideo();
});
var stopButton2 = document.getElementById("stop-button2");
stopButton2.addEventListener("click", function () {
player2.stopVideo();
});
}
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
I already know how to play/pause a YouTube video dynamically as you can see from my weave.
However I'm having difficulty getting it to work dynamically with FancyBox using onBlur (when the window is not focused video should pause).
Here's my Pen: http://codepen.io/anon/pen/wJXoJy?editors=0010
// Show Lightbox Video Onload
$.fancybox.open({
youtube : {
controls : 0,
showinfo : 0
},
src : '//www.youtube.com/embed/-AszZcClVXA?enablejsapi=1', // Source of the content
type : 'iframe', // Content type: image|inline|ajax|iframe|html (optional)
});
// 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);
var player;
function onYouTubePlayerAPIReady(e) {
// create the global player from the specific iframe (#video)
player = new YT.Player($(".fancybox-iframe").attr("id"), {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
window.addEventListener("blur", function() {
player.pauseVideo();
});
}
<link rel="stylesheet" href="//www.fancyapps.com/fancybox/3/fancybox/jquery.fancybox.min.css?v=1490320405" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//www.fancyapps.com/fancybox/3/fancybox/jquery.fancybox.min.js?v=1490320405"></script>
Here is a demo - http://codepen.io/fancyapps/pen/jBKowp?editors=1010
Basically, idea is that you initialize fancyBox after YouTube API is available and then you can use YouTube API methods inside fancyBox callback.
// 1. 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);
// 2. This function initializes fancyBox
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
$('[data-fancybox="group"]').fancybox({
onComplete : function( instance, current ) {
if ( current.type === 'iframe' ) {
var id = current.$content.find('iframe').attr('id');
player = new YT.Player( id, {
events : {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
});
}
// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 4. Fires when the player's state changes.
function onPlayerStateChange(event) {
// Go to the next video after the current one is finished playing
if (event.data === 0) {
$.fancybox.getInstance('next');
}
}
// Page Visibility API to pause video when window is not active
$(document).on("visibilitychange", function() {
if ( player ) {
if ( document.hidden ) {
player.pauseVideo();
} else {
player.playVideo();
}
}
});
You're only pausing the video on blur. Why not use mouseover event to play and mouseout event to pause the video?
Somewhat related to:
YouTube IFrame API doesn't always load?
But different in that I AM loading the YouTube script per instructions. Note, in my source, the iframe is ABOVE the script block in the load order. I based this off of these instructions (below). The example works fine if I'm on that page, but doesn't seem to work for me when I put the code on mine. I'm sure I'm missing something really simple but I'm to be missing it. Thanks!
https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Console shows this script is loading
var player;
function onYouTubeIframeAPIReady() {
console.log("onYouTubeIframeAPIReady", arguments); //This shows in console
player = new YT.Player('js_youTubeFrame', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log("onPlayerReady",event); //Never triggers
}
function onPlayerStateChange(event) {
console.log("onPlayerStateChange", event); //Never triggers
if (event.data === YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!"); //Never triggers
}
}
<div id="js_youTubeContainer" class="embed-responsive embed-responsive-16by9">
<iframe id="js_youTubeFrame" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/u3A7bmEOtaU?enablejsapi=1&rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
Best way to load a Youtube Video by his API, is following this sintaxis:
<div id="video-youtube"></div>
<script id="youtube-tracking-script">
var youtubeVideoId = 'u3A7bmEOtaU'; // replace with your own video id
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementById("youtube-tracking-script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var video;
function onYouTubeIframeAPIReady() {
video = new YT.Player('video-youtube', {
height: '352',
width: '100%',
videoId: youtubeVideoId,
playerVars: {rel: 0, showinfo: 0},
events: {
'onStateChange': videoPlay
}
});
}
function videoPlay(event) {
if (event.data == YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!");
}
if (event.data == YT.PlayerState.PAUSED) {
console.log("YouTube Video is PAUSED!!");
}
if (event.data == YT.PlayerState.ENDED) {
console.log("YouTube Video is ENDING!!");
}
}
</script>
https://jsfiddle.net/t4qwfk0d/1/
You should replace your <iframe> </iframe> to <div id= "js_youTubeFrame"> </div>, in my case it works.
I think that Youtube Iframe Api needs that div to convert it on iframe after.
I want to autoplay videos that are muted on my website. I found some code which seemed to work, but it doesn't. Why doesn't this javascript and HTML code work?
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_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;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
playerVars: { 'autoplay': 1, 'controls': 1,'autohide':1,'wmode':'opaque' },
videoId: 'RDfjXj5EGqI',
events: {
'onReady': onPlayerReady}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
} </script>
jsFiddle for testing: https://jsfiddle.net/qswpr8tL/
Thanks!
Please build your onReady handler just like that:
var player;
// ...
function onPlayerReady(event) {
player.mute();
}
According documentation you have to call mute method on player object.
I have an embedded YouTube videos in my HTML page. I'm trying to get the current time of YouTube video. I used the answer of that question to create page like this
(YouTube currentTime with jQuery)
When I'm trying to display the time I'm getting an error: 'getCurrentTime is not a function'.
HTML
<div style="text-align:center">
<button onclick="playPause()">Play</button>
<button onclick="showTime()">Show Time</button>
<br><br>
<iframe id = "it" width="560" height="315" src="https://www.youtube.com/v/FHtvDA0W34I?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br>
<label id=startHighlighlbl>VideoHighlightStart: </label>
</div>
JavaScript
<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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function ShowTime() {
alert(player.getCurrentTime());
}
</script>
You should load your video through the YT-API, so player is initialized correctly and thus accessible through the API. Basically you need to remove your iframe from your HTML and instead let YT-API create the iframe for you.
Try the following:
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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('it', {
height: '315',
width: '560',
videoId: 'FHtvDA0W34I',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
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();
}
function ShowTime() {
alert(player.getCurrentTime());
}
<body>
<button onclick="ShowTime()">Show Time</button>
<br>
<div id="it"></div>
</body