JavaScript to control play/pause embedded YouTube videos - javascript

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);

Related

youtube autoplay is not working

I am using youtube embed to display a video. I need to autoplay when site is opened
<iframe class="slider-image-mockup align-center" width="100%" height="750" src="https://www.youtube-nocookie.com/embed/Y-p828Jy8C8?rel=0&controls=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8&showinfo=0" frameborder="0" allow="autoplay; loop; encrypted-media" allowfullscreen></iframe>
I am using this code before it was working fine but for past few days. Autoplay is not working...
It may sound crazy but I didn't change anything in my code.
its showing like below after clicking of play button only video is playing
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. 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 done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
now I have changed the url
from : https://www.youtube-nocookie.com/embed/Y-p828Jy8C8?rel=0&controls=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8&showinfo=0
To : https://www.youtube.com/embed/Y-p828Jy8C8?rel=0&controls=0&showinfo=0&autoplay=1&loop=1&playlist=Y-p828Jy8C8
now its working... Thank you..

youtube iframe api not pausing video

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

YouTube autoplay with mute

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.

jQuery Mobile Popup with custom YouTube Controls

I would like to create a jQuery Mobile Popup (or any type of javascript modal) which embeds a YouTube Video and allows for custom controls.
Here is a JSFiddle demo with a basic "Play" button which hopefully helps demonstrate my problem.
Basically, I have the iframe code in HTML:
<iframe id="iframe-video" width="400" height="300" src="http://www.youtube.com/embed/a0gact_tf_0" frameborder="0" allowfullscreen></iframe>
And then, when the video is loaded I do this:
$(document).on("pagecreate", function() {
// bind click events
$(document).on('click', '#play', function() {
playVideo();
return false;
});
$(".ui-popup iframe")
.attr("width", 0)
.attr("height", "auto");
$("#popupVideo").on({
popupbeforeposition: function() {
initYoutubePlayer();
// call our custom function scale() to get the width and height
var size = scale(497, 298, 15, 1),
w = size.width,
h = size.height;
$("#popupVideo iframe")
.attr("width", w)
.attr("height", h);
},
popupafterclose: function() {
$("#popupVideo").html("<span></span>");
$("#popupVideo iframe")
.attr("width", 0)
.attr("height", 0);
},
});
});
function initYoutubePlayer() {
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() {
alert('onYouTubeIframeAPIReady');
player = new YT.Player('iframe-video', {
events: {
'onReady': onPlayerReady,
}
});
};
function onPlayerReady(event) {
alert('ready');
};
alert('initialized');
}
function playVideo() {
alert('playVideo...');
//player.playVideo();
}
Loading the video works fine but I can't get the YouTube iFrame API working where I can instantiate the YT.Player. In other words, 'onYouTubeIframeAPIReady' does not fire.
I have tried all sorts of permutations of this JSFiddle code but feel like I may be missing something obvious.
Is it possible to have custom YouTube controls within a jQuery Mobile Popup or javascript modal?
SEE FIDDLE
<!DOCTYPE html>
<title>JQM latest</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css" rel="stylesheet" type="text/css" />
<body>
<div data-role="page" id="index">
Launch video player
<div data-role="popup" id="popupVideo" data-overlay-theme="b" data-theme="a" data-tolerance="15,15" class="ui-content">
Play
<br>
<div id="player"></div>
<!-- <iframe src="http://player.vimeo.com/video/41135183?portrait=0" width="497" height="298" seamless=""></iframe> -->
</div>
</div>
</body>
<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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'a0gact_tf_0',
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {}
function stopVideo() {
player.stopVideo();
}
$(document).on('click', '#play', function() {
player.playVideo();
});
</script>
</html>

Lazy Load youtube video from iframe API

I want to lazy load the youtube video with iframe API. ie. load only the poster image in the beginning and when user clicks on it then only load the actual image and its content.
Most of this is taken from the getting started section on the youtube page.
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. 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 done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
This example loads the video when it is ready.
So we change it up a bit to add in a placeholder image and on click hide the image and play the video.
Wrap the tag (step 2) in function
function loadYT() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
Add an image Check this question for more details on sizes.
<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
Then on click hide the placeholder image and load the player
document.getElementById("placeholder").addEventListener("click", function(){
this.style.display = 'none';
loadYT()
});
Final result can be seen below.
<div id="placeholder">
<img src="http://img.youtube.com/vi/M7lc1UVf-VE/sddefault.jpg" />
</div>
</div>
<div id="player"></div>
<script>
document.getElementById("placeholder").addEventListener("click", function(){
this.style.display = 'none';
loadYT()
});
// 2. This code loads the IFrame Player API code asynchronously.
function loadYT() {
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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. 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 done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
Why load the videos on click, and not just when the user sees them? Use jQuery.Lazy and you have nothing more to do. :)
Add the Plugin to your Page: (you will need jQuery or Zepto as well)
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.youtube.min.js"></script>
Prepare your iFrames: (note the data-loader and data-src attributes)
<iframe data-loader="youtube" data-src="1AYGnw6MwFM" width="560" height="315"></iframe>
And start using Lazy:
$(function() {
$("iframe[data-src]").Lazy();
});
That's it! The iFrames will be loaded whenever the user reaches them by scrolling. More inormations here.
<iframe loading="lazy"
This HTML feature allows lazy loading YouTube iframe embeds only when the user scrolls over them, without any extra JavaScript (the YouTube video is of course automatically loaded via JavaScript in the iframe however).
Here is a working jsfiddle: https://jsfiddle.net/cirosantilli/3p0tk5nc/1/ that I have tested on Chromium 81. You can see on the developer tools "network" tab that the frames only load when you scroll over them.
It does not work on Stack Overflow snippets for some reason however because YouTube videos appear to not work on Stack Overflow in general, not because of loading="lazy" in particular.
More details at: lazy load iframe (delay src http call) with jquery
How about this?
HTML
<div class="wrapper">
<ul>
<li><a title="video 1" data-video="http://www.youtube.com/embed/X0DeIqJm4vM">Motherlover</a></li>
<li><a title="video 2" data-video="http://www.youtube.com/embed/GI6CfKcMhjY">Jack Sparrow</a></li>
<li><a title="video 3" data-video="http://www.youtube.com/embed/TcK0MYgnHjo">Ras trent</a></li>
<li><a title="video 4" data-video="http://www.youtube.com/embed/8yvEYKRF5IA">Boombox</a></li>
<li><a title="video 5" data-video="http://www.youtube.com/embed/6_W_xLWtNa0">Shy Ronnie 2</a></li>
</ul>
<iframe id="videoArea" width="350" height="250" src="http://www.youtube.com/embed/X0DeIqJm4vM" frameborder="0" allowfullscreen></iframe>
</div>
JS
var initVideos = function() {
var videoArea = $("#videoArea"),
divs = $("ul li a"); // or some other data format
// bind your hover event to the divs
divs.click(function(ev) {
ev.preventDefault();
videoArea.prop("src", $(this).data('video'));
divs.removeClass("active");
$(this).addClass("active");
});
};
// once the DOM is ready
$(function() {
initVideos();
});
DEMO
I just lazy load the thumbnail and only load the real video if the visitor is hovering the thumbnail. For Privacy reasons you can also make him click a confirmation before loading the video from youtube.
<?php $youtubevideo="Video ID1"; $youtubezaehler=$youtubezaehler+1;?>
<br>
<div align="center" class="video-container" onmouseover="video<?php echo($youtubezaehler);?>()">
<div style="position:relative;">
<img loading="lazy" id="vorschaubild<?php echo($youtubezaehler);?>" class="" src="https://img.youtube.com/vi/<?php echo($youtubevideo);?>/<?php echo $youtube_aufloesung; ?>" width="100%" alt="Lade...">
<div id="play<?php echo($youtubezaehler);?>" style="position:absolute; top:30%; left:46%; width:10%;"><img src="play.gif" alt="Play" style="width:100%;"></div>
</div>
<script type="text/javascript">
<!--
//JavaScript zum DSGVO konformem und Ladezeitoptimierten Einbinden der Youtube Videos erst bei Nutzung
function video<?php echo($youtubezaehler);?>() {
if(document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility=="hidden") return false; //Damit das Video nicht beim abspielen versehntlich neu geladen wird
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").height = "1px";
document.getElementById("vorschaubild<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("play<?php echo($youtubezaehler);?>").style.visibility="hidden";
document.getElementById("video<?php echo($youtubezaehler);?>").src = "https://www.youtube-nocookie.com/embed/<?php echo($youtubevideo);?>?rel=0";
}
// -->
</script>
<iframe title="Video" id="video<?php echo($youtubezaehler);?>" src="" frameborder="0" allowfullscreen></iframe>
</div>
Finally it worked, below code is in angularJS.
HTML
<div data-ng-repeat="video in videoIds track by $index">
<div id="uniQueId" ng-click="playVideo(video, 'player' + $index)">
<div class="video-play-button"></div>
</div>
</div>
JS
$scope.playVideo = function(videoId, id) {
$scope.players[id] = new YT.Player(id, {
videoId: videoId,
width: '400',
height: '300',
playerVars: { 'autoplay': 1 },
events: {
'onStateChange': $scope.onPlayerStateChange
}
});
};

Categories