How to allow play only one embedded YouTube video on page? - javascript

I have a few embedded YouTube videos on my page:
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/4LaUVEF9GTs?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/JYZ_oP7QVSY?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
How to avoid playing several videos at the same time if user press play button in all videos?
Thank you for any suggestions or ideas in advance.

Here's a quick YouTube player manager sketch that you can adapt to your needs. A couple of quick notes:
You can also use the API to programmatically embed each iframe. This example assumes that the iframe elements are already on the page.
If (as with this example) you utilize already embedded players then make sure you append '?enablejsapi=1' to the end of the embed URL.
Essentially this manager keeps track of the registered videos. If it detects that a registered video begins to play it will pause any other registered video that is currently playing.
API Reference: https://developers.google.com/youtube/iframe_api_reference
UPDATE:
Changed the example to use pauseVideo vs. stopVideo.
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 ytPlayerManager = (function YTPlayerManager() {
var players = [],
PLAYING = 1;
function register(id) {
players.push({
id: id,
player: makePlayer(id)
});
}
function makePlayer(id) {
return new YT.Player(id, {
events: {
'onStateChange': function(event) {
if(event.data == PLAYING) {
videoPlaying(id);
}
}
}
});
}
function videoPlaying(id) {
players.forEach(function(item) {
if(item.id !== id) {
item.player.pauseVideo();
}
});
}
return { register };
})();
function onYouTubeIframeAPIReady() {
ytPlayerManager.register('video1');
ytPlayerManager.register('video2');
ytPlayerManager.register('video3');
}

You need to use youtube api to have the full control over the videos and you can generate videos.
so you will be able to stop the others if one is playing
onStateChange
This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible values are:
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued).
When the player first loads a video, it will broadcast an unstarted (-1) event. When a video is cued and ready to play, the player will broadcast a video cued (5) event. In your code, you can specify the integer values or you can use one of the following namespaced variables:
YT.PlayerState.ENDED
YT.PlayerState.PLAYING
YT.PlayerState.PAUSED
YT.PlayerState.BUFFERING
YT.PlayerState.CUED
example :
window.onYouTubePlayerAPIReady = function(){
var player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
src is here
I hope it will helps

Considering your code:
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/4LaUVEF9GTs?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/JYZ_oP7QVSY?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
Through this implementation, you will not need to define the identification of iframes or store many players in the memory. You just need to store the last iframe played.
Insert this script before using any function related to the Youtube iframe api.
<script src="https://www.youtube.com/iframe_api"></script>
If you're using an iframe directly on html, then append "enablejsapi=1" and your websites origin, in the iframe sources url parameters in all your iframe sources. Like this:
<iframe id="video_player" src="https://www.youtube.com/embed/VIDEO_ID?enablejsapi=1&origin=https://example.com"></iframe>
You can choose to "pauseVideo" or "stopVideo", in 'postMessage' method, of the following implementation:
var playedVideoIframe = false;
function onYouTubeIframeAPIReady() {
const IFRAMES = document.getElementsByTagName('iframe');
generatePlayers(IFRAMES);
}
function generatePlayers(IFRAMES) {
for (const IFRAME of IFRAMES) {
if (IFRAME.src.includes('youtube')) {
new YT.Player(IFRAME, {
events: {
'onStateChange': onPlayerStateChange
}
});
}
}
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
const PLAYING_VIDEO_IFRAME = event.target.h;
pauseLastPlayedVideo(PLAYING_VIDEO_IFRAME);
playedVideoIframe = PLAYING_VIDEO_IFRAME;
}
}
function pauseLastPlayedVideo(PLAYING_VIDEO_IFRAME) {
if (playedVideoIframe && playedVideoIframe.src != PLAYING_VIDEO_IFRAME.src) {
playedVideoIframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
Need more help? Read the documentation on https://developers.google.com/youtube/iframe_api_reference

If you embed as HTML, try this:
<div style="text-align: center; margin: auto">
<iframe width="640" height="360" src="http://www.youtube.com/embed/abdcefg?
border=1& rel=0& showsearch=0& version=3&
modestbranding=1& fs=1" frameborder="0" allowfullscreen>
</iframe>
<param name="allowFullScreen" value="true" />
<param name="allowscriptaccess" value="false" />
</div>

Related

Embed Youtube Videos Mute on / off button

I want to have a mute button for my site, so when it's pressed it will unmute / mute the audio playing from the background video.
The js I have rn is this. Is there any way I can implement a button with this code?
`enter code here
var videos = [
'D1sZ_vwqwcE',
'BC_Ya4cY8RQ',
'HPc8QMycGno',
'JDglMK9sgIQ',
'hgKDu5pp_fU',
'oKMNj8v2gKE',
'TfnRTifSWh0',
'xO3aB5C3dpQ',
'v5hepekcHkk',
'4kjpZ_sPxzc',
];
var index=Math.floor(Math.random() * videos.length);
var html='<div class="video-background"><div class="video-foreground"><iframe frameborder="0" src="https://www.youtube.com/embed/' +videos[index] + '?controls=1&showinfo=0&rel=0&autoplay=1&iv_load_policy=3&&mute=1" allow="autoplay""></iframe></div></div>';
document.write(html);
site for reference: https://enph.la
I deserve no credit for this answer, but wanted to point out that the described issue actually got solved in Custom mute/unmute button Youtube API quite well using the YouTube API as it can be seen in this working example from Marco Aurelio Fernandez Reyes
(somehow it just works on jsfiddle, but not on stackoverflow...):
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('youtube-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
console.log("hey Im ready");
//do whatever you want here. Like, player.playVideo();
}
function onPlayerStateChange() {
console.log("my state changed");
}
document.getElementById("mute").addEventListener('click', function(event) {
console.log(player);
if (player.isMuted()) {
player.unMute();
} else {
player.mute();
}
});
#mute {
width: 50px;
height: 50px;
background-color: red;
}
<iframe id="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&
autoplay=1
&disablekb=1
&enablejsapi=1
&loop=1
&controls=0
&mute=0" frameborder="0" enablejsapi="1" allowfullscreen></iframe>
<div id="mute">
</div>
<p>
Press red square to mute/unmute
</p>
Since a comment easily be overlooked, I just wanted to point out the working solution.

Angular 2+ Youtube Iframe API with existing iframe [src] binding failing to run events

I am having an issue with the youtube iframe API not running event callbacks on an existing iframe.
If I use:
<div id="player"></div>
It works
But if I use:
<iframe id="player" [src]="mainVideo | sanitize"
width="560" height="315" frameborder="0" allowfullscreen></iframe>
It does not load any of the event callbacks like autoplay or alerting when the person has finished the video.
HTML
<iframe id="player" [src]="mainVideo | sanitize"
width="560" height="315" frameborder="0" allowfullscreen></iframe>
Typescript
ngAfterViewInit() {
const doc = (<any>window).document;
let script = doc.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.youtube.com/iframe_api';
doc.body.appendChild(script);
console.log(script);
}
ngOnInit() {
(<any>window).onYouTubeIframeAPIReady = () => {
console.log((<any>window).YT);
this.player = new (<any>window).YT.Player('player',
{
events: {
'onReady': (e) => {
e.target.playVideo();
},
'onStateChange': (e) => {
if (e.data === 0) {
alert('done');
}
}
}
});
}
}
MainVideo
this.mainVideo = "http://www.youtube.com/embed/"
+ this.sect[0].mainVideoUrl + "?origin=http://localhost:56194&enablejsapi=1";
Can anyone help me understand why its ocurring? The video itself plays when you click play, but it does not autoplay and it does not alert the user when the video is finished.
Thanks!

How to play youtube with JS after a timeout?

I have a youtube video on my website and want it to start playing after 5 sec user is on my site.
Is it possible with JS / jQuery? Anyhow?
Check this link http://codepen.io/martinwolf/pen/dyLAC
You just need to replace the below code in above link
$('#play-video').on('click', function(ev) {
$("#video")[0].src += "&autoplay=1";
ev.preventDefault();
});
with
setTimeout(function(ev) {
$("#video")[0].src += "&autoplay=1";
ev.preventDefault();
}, 5000);
I recommend you to use correct way to do this.
For example, you can do it with pure JS and YouTube Player API:
<iframe id="player" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" width="400" height="300"></iframe>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
setTimeout(function() {
event.target.playVideo();
}, 5000)
}
</script>
Here is fiddle: https://jsfiddle.net/hv4bpbys/2/
You can find more information here
It is really simple :
setInterval(function(e){
$('#video')[0].src += '?autoplay=1';
e.preventDefault();
}, 5000);
<iframe id="video" width="560" height="315" src="https://www.youtube.com/embed/2mWaqsC3U7k" frameborder="0" allowfullscreen></iframe>
Check this JS Fiddle

YouTube API OnStateChange Listener Stops Working After Switch SRC Attr

I am trying to change the video playing in the YouTube iframe in the cleanest way possible and a few months ago I had this code working, but YouTube changed their API and it stopped working for me. Now the onPlayerStateChange event is not firing after I switch out the video's SRC attribute to switch the video that is playing. I'm an amateur to coding so I may be missing something simple here, but any input would be greatly appreciated.
Below is a code that loads a YouTube video and when it ends, there's an alert that automatically pops up for you. However, when you click the button and switch the video by switching out the SRC attribute, the alert function stops working and its as if the entire onPlayerStateChange function stops working. I could not get it working in jsfiddle, but a link to a live demo can be found at http://thetunedrop.com/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
</body>
</html>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.22.custom.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
function load_ytid(youtubeid){
$("#player").attr("src", "http://www.youtube.com/embed/" + youtubeid + "?fs=1&autoplay=1");
}
$(document).ready(function(){
$(".button").on("click", function(){
var youtubeid = $(this).data("youtubeid");
load_ytid(youtubeid);
});
});
</script>
Try this instead :
<!DOCTYPE html>
<html>
<body>
<script src="jquery-1.10.2.min.js"></script>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
<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: '0Bmhjf0rKe8',
playerVars: { 'autoplay': 1, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
playerReady = true;
}
// 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.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
alert('done');
}
}
$(".button").on("click", function(){
player.loadVideoById("Vw4KVoEVcr0", 0, "default");
});
</script>
</body>
</html>
The fiddle here : http://jsfiddle.net/QtBlueWaffle/8bpQ8/1/
Hope this helps
I had kind of the same problem (I Think)... I wanted the user to be able to change the content for multiple players, and this is what works for me: I call the youtube api with a onload function additional to the new Youtubelink, so that reloads every time the iframe changes.
MY HTML:
<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/0Bmhjf0rKe8
?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"
frameborder="0" allowfullscreen> </iframe>
MY JS:
function floaded1() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': function (event) {
if (event.data == 0) {
alert('done');
};
}
}
});
}
WHAT I LOAD WITH A VIDEO PICKER:
html += '<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&
showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen>
</iframe>';

play iframe video on click a link javascript

I have used a iframe video in my web page. This is my html code
<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play video
I need to play video onclick the play video link. How can i do that?
This works, it appends autoplay=1 to the url causing the video to start playing.
addendum: If your video's source does not already have a querystring then it would be prudent to add a ? instead of a &, as is sometimes the case. This can be done by looking for its existence.
<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play video
<script>
//use .one to ensure this only happens once
$("#playvideo").one(function(){
//as noted in addendum, check for querystring exitence
var symbol = $("#video1")[0].src.indexOf("?") > -1 ? "&" : "?";
//modify source to autoplay and start video
$("#video1")[0].src += symbol + "autoplay=1";
});
</script>
However, most people inherently understand that if they want a video to play, they will just click on it and I would suggest just leaving that to them or starting the video off with autoplay.
Also need to mention that autoplay does not work on mobile devices (powered by Android or iOS)
I correctly set in end src - ?autoplay=1
<iframe id="video1" width="450" height="280" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
Play button
<script>
$("#playvideo").click(function(){
$("#video1")[0].src += "?autoplay=1";
});
</script>
Here is another example. Check this here: https://codepen.io/rearmustak/pen/VXXOBr
const Player = document.getElementById('player2');
const PlayBtn = document.getElementById('play');
const stopBtn = document.getElementById('stop');
let times = 0, playY;
const playVideo = PlayBtn.addEventListener( 'click' , () => {
if(times == 0){
playY = Player.src += '?autoplay=1';
times = 1;
}
});
stopBtn.addEventListener( 'click' , () => {
playY = playY.slice(0, -11);
Player.src = playY
times = 0;
});
.video-frame{
overflow: hidden;
margin-bottom: 10px;
}
button{
border: none;
background-color: #e75252;
color: #ffffff;
padding: 10px 15px;
border-radius: 3px;
cursor: pointer;
}
button:focus{
outline: 0;
}
#stop{
background-color: #ff0002;
}
<h1>Youtube video Play/Stop</h1>
<div class="video-frame">
<iframe id="player2" width="560" height="315" src="https://www.youtube.com/embed/cs1e0fRyI18" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<button id="play">Play</button>
<button id="stop">Stop</button>
since the first answer is already 3 years old, let me point to the Youtube Player API. With that you can remote control your embedded player.
See https://developers.google.com/youtube/iframe_api_reference?hl=en
With a small adjustment, you can start the video via link and without reloading the entire iframe:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<!-- The Play-Link will appear in that div after the video was loaded -->
<div id="play"></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();
document.getElementById('play').innerHTML = 'Play Video';
}
function play(){
player.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>
here is link to example http://jsfiddle.net/WYwv2/5/
Check out this
<!DOCTYPE html>
<html>
<body>
Play video
<iframe id="video1" width="520" height="360" frameborder="0" ></iframe>
<script>
function playme() {
document.getElementById("video1").src = 'http://www.w3schools.com/tags/mov_bbb.mp4';
}
</script>
</body>
</html>
​
We set the source of video dynamically.
it's work for me.
please Check out this.
$("#player").on("pause", function(e) {
clearTimeout(playTimeout);
});
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', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
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, 2000);//replace time here
$("#player").get(0).load();
$("#player").get(0).pause();
done = true;
}
}
function stopVideo() {
player.stopVideo();
}

Categories

Resources