fullscreen vimeo trigger event on customize button - javascript

Is there a way to trigger fullscreen mode on Vimeo player using JavaScript ?
I want to hide all controls of player and i have a side Customize button that i want trigger fullscreen.
<script src="//f.vimeocdn.com/js/froogaloop2.min.js"></script>
<iframe id="player1" src="//player.vimeo.com/video/76979871?api=1&player_id=player1" width="630" height="354" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<div>
<button>Play</button>
<button>Pause</button>
<button class="fullscreen">FullScreen</button>
</div>
$(function() {
var iframe = $('#player1')[0];
var player = $f(iframe);
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
status.text('ready');
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
// button to trigger fullscreen
$('button.fullscreen').bind('click', function() {
// here i want trigger fullscreen on player Vimeo
});
});

Unfortunately, no. The Fullscreen API requires a direct user action and that action is lost on the postMessage to the player.

Set the embed iframe size at 100% for width and height and put it in a div. Then, you can manage the div size.
It's not a real fullscreen but it can use all the size of your browser window.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="video">
<!-- embed here --------------- -->
<iframe
src="https://player.vimeo.com/video/391669239?h=0b278c0322"
width="100%"
height="100%"
allowfullscreen
frameborder="0"
>
</iframe>
<!-- -------------------------- -->
</div>
<button id="fs1" onclick="setFullScreen(1)" >Full screen</button>
<button id="fs0" onclick="setFullScreen(0)" >Windowed</button>
</body>
</html>
/////////////////////////////////////////////////////
function setFullScreen(onoff) {
// onoff :
// 0 windowed
// 1 full screen
let o = document.getElementById('video');
if(onoff === 0) {
o.style.position = "";
o.style.top = "";
o.style.left = "";
o.style.width = "200px";
o.style.height = "100px";
} else if(onoff === 1) {
o.style.position = "absolute";
o.style.top = "0";
o.style.left = "0";
o.style.width = "100%";
o.style.height = "100%";
}
}
https://jsfiddle.net/k06pr4L7/

Related

How to disable "related videos" from an embedded youtube playlist

I need to embed a Youtube playlist on an iframe. I don't want the user to be able to exit this playlist, so I need to disable the "related video" and "more video" features (the one that shows more videos when the video is stopped and the one that shows them when the video is finished).
I've tested some workarounds but they only used to work for single videos (not playlist) and most of them stopped working after they changed the way ?rel=0 behaves. Is there any way to do this?
This is my code:
.rep {
position: absolute;
top: 0px;
left: 0px;
width: 1280px;
height: 640px;
z-index: 6;
}
<iframe class="rep" src="https://www.youtube.com/embed/videoseries?list=PLUl4u3cNGP63gFHB6xb-kVBiQHYe_4hSi" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
EDIT: The videos must be shown in order, therefore I can't use rel to display only videos from the playlist. Plus, if you click on them a youtube page outside of the iframe will appear.
If I look through the YouTube Embedded Players and Player Parameters docs, there is no such thing to order the more videos section if you pause the video.
The two parameters I suggest to get near as possible to your goal is:
You can add:
listType=playlist
rel=0 to turn off related videos from the more videos section.
Note: The behaviour of rel=0 will be removed after September 25, 2019.
Conclusion:
It seems like what you want to achieve is not possible. With the default embed iframe of YouTube.
You might want to consider to look to other players with playlist options. Something like JW Player note that you need a licence for this player, JW Player playlist docs. I did some reading on JW Player as well, they currently don't support YouTube videos.
But maybe there are other players that have the same functionally for free.
If you add &rel=0 at the end of playlist link - in related videos will be showed only videos from your playlist. Example:
<iframe class="rep" src="https://www.youtube.com/embed/videoseries?list=PLUl4u3cNGP63gFHB6xb-kVBiQHYe_4hSi&rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
If you remove &rel=0 from the link, it show random videos from youtube
Update for 2021
Youtube now seems to have a loop function that can be used to git rid of “related videos”. What it does basically is that when your video ends, it restarts again instead of showing (un)related videos. It worked perfectly in my case. Here is the code:
https://www.youtube.com/embed/VIDEO_ID?playlist=VIDEO_ID&loop=1
Please make sure to replace both VIDEO_ID in the code with your video ID. N̲o̲ N̲e̲e̲d̲ for creating a playlist
Example of full iframe code with player controls being enabled
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID?playlist=VIDEO_ID&loop=1" title="YouTube video player" rel="0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Example of full iframe code with player controls being disabled
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID?playlist=VIDEO_ID&loop=1&controls=0" title="YouTube video player" rel="0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Here is a work around not the best but it will stop them annoy recommendations. It loops the playlist never giving youtube a chance to stop and give you there recommendations to get users back to youtube. This has worked well for me. If you see it plays my list in the loop and then plays the next, all without ever bringing up the recommendations. if you stop it it just stays there. Hope it helps they key is 0&loop
https://codesandbox.io/s/adoring-tereshkova-nwv8i
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<iframe width="100%" height="425" src="https://www.youtube.com/embed/HdEN2JinZVE?autoplay=&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>
<script src="src/index.js">
</script>
</body>
</html>
It can not be done after September 25, 2018. The effect of the change is that you will not be able to disable related videos. Below is the YouTube official post link of it.
Official Link: https://developers.google.com/youtube/player_parameters#release_notes_08_23_2018
Thanks
I just found a great website that found a fix for your problem. The code is a bit long, but I think it works. They have an example if you scroll up a bit. https://www.maxlaumeister.com/blog/hide-related-videos-in-youtube-embeds/#hideyt-embed-code
<!-- https://maxl.us/hideyt -->
<style>
.hytPlayerWrap {
display: inline-block;
position: relative;
}
.hytPlayerWrap.ended::after {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
cursor: pointer;
background-color: black;
background-repeat: no-repeat;
background-position: center;
background-size: 64px 64px;
background-image: url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiB2aWV3Qm94PSIwIDAgNTEwIDUxMCI+PHBhdGggZD0iTTI1NSAxMDJWMEwxMjcuNSAxMjcuNSAyNTUgMjU1VjE1M2M4NC4xNSAwIDE1MyA2OC44NSAxNTMgMTUzcy02OC44NSAxNTMtMTUzIDE1My0xNTMtNjguODUtMTUzLTE1M0g1MWMwIDExMi4yIDkxLjggMjA0IDIwNCAyMDRzMjA0LTkxLjggMjA0LTIwNC05MS44LTIwNC0yMDQtMjA0eiIgZmlsbD0iI0ZGRiIvPjwvc3ZnPg==);
}
.hytPlayerWrap.paused::after {
content: "";
position: absolute;
top: 70px;
left: 0;
bottom: 50px;
right: 0;
cursor: pointer;
background-color: black;
background-repeat: no-repeat;
background-position: center;
background-size: 40px 40px;
background-image: url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEiIHdpZHRoPSIxNzA2LjY2NyIgaGVpZ2h0PSIxNzA2LjY2NyIgdmlld0JveD0iMCAwIDEyODAgMTI4MCI+PHBhdGggZD0iTTE1Ny42MzUgMi45ODRMMTI2MC45NzkgNjQwIDE1Ny42MzUgMTI3Ny4wMTZ6IiBmaWxsPSIjZmZmIi8+PC9zdmc+);
}
</style>
<div class="hytPlayerWrapOuter">
<div class="hytPlayerWrap">
<iframe width="640" height="360" src="https://www.youtube.com/embed/`**YOUR VIDEO ID HERE**`?rel=0&enablejsapi=1" frameborder="0"></iframe>
</div>
</div>
<script>
"use strict";
document.addEventListener('DOMContentLoaded', function () {
if (window.hideYTActivated) return;
let onYouTubeIframeAPIReadyCallbacks = [];
for (let playerWrap of document.querySelectorAll(".hytPlayerWrap")) {
let playerFrame = playerWrap.querySelector("iframe");
let tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
let firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let onPlayerStateChange = function (event) {
if (event.data == YT.PlayerState.ENDED) {
playerWrap.classList.add("ended");
} else if (event.data == YT.PlayerState.PAUSED) {
playerWrap.classList.add("paused");
} else if (event.data == YT.PlayerState.PLAYING) {
playerWrap.classList.remove("ended");
playerWrap.classList.remove("paused");
}
};
let player;
onYouTubeIframeAPIReadyCallbacks.push(function () {
player = new YT.Player(playerFrame, {events: {'onStateChange': onPlayerStateChange}});
});
playerWrap.addEventListener("click", function () {
let playerState = player.getPlayerState();
if (playerState == YT.PlayerState.ENDED) {
player.seekTo(0);
} else if (playerState == YT.PlayerState.PAUSED) {
player.playVideo();
}
});
}
window.onYouTubeIframeAPIReady = function () {
for (let callback of onYouTubeIframeAPIReadyCallbacks) {
callback();
}
};
window.hideYTActivated = true;
});
</script>
In my case this is working you can try this :
https://www.youtube-nocookie.com/embed/{videoId}?rel=0&showinfo=0
Unfortunately, external CSS or JS can't be applied to iframe videos or iframe contents in a webpage.
For now, you can add rel=0 parameter to the video URL in iframe code. As per youtube documentations, rel=0 parameter will be disabled after Sep 25 2019.
Here is an example with rel=0 parameter
<iframe width="560" height="315" src="https://www.youtube.com/embed/J8Rt6HSzrqY&rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
You can also use the playlist feature or parameter. See example below:
<iframe width="560" height="315" src="https://www.youtube.com/embed/videoseries?list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG&rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
Above code is taken from Official Youtube Support documents. You can add only one video in the list so that it does not play any other video after the current video finishes.
Based on the work of Maximillian Laumeister hideyt I forged a JS which can be included anywhere and autoamtically wraps its magic around every embedded youtube iframe you have.
hideYTrel.js
"use strict";
if (document.readyState !== 'loading') init();
else document.addEventListener('DOMContentLoaded', init);
function init() {
if (window.runOnce) return;
if (typeof YT === 'undefined') {
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 iframes = [];
for (var iframe of document.querySelectorAll("iframe[src]")) {
var src = iframe.getAttribute("src");
if (src.includes("youtube.com/embed/")) {
if(!src.includes("enablejsapi=1"))
if(src.includes("?"))
iframe.setAttribute("src", src + "&enablejsapi=1");
else
iframe.setAttribute("src", src + "?enablejsapi=1");
iframes.push(iframe);
}
}
var overlayStyles = {
display: "none",
content:"",
position: "absolute",
left: 0,
right: 0,
cursor: "pointer",
backgroundColor: "black",
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
};
window.onYouTubeIframeAPIReady = function() {
iframes.forEach(function(iframe) {
var overlay = document.createElement('div');
for (var style in overlayStyles) {
overlay.style[style] = overlayStyles[style];
}
var wrapper = document.createElement('div');
wrapper.style.display = "inline-block";
wrapper.style.position = "relative";
iframe.parentNode.insertBefore(wrapper, iframe);
wrapper.appendChild(overlay);
wrapper.appendChild(iframe);
var onPlayerStateChange = function(event) {
if (event.data == YT.PlayerState.ENDED) {
overlay.style.backgroundImage = "url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiB2aWV3Qm94PSIwIDAgNTEwIDUxMCI+PHBhdGggZD0iTTI1NSAxMDJWMEwxMjcuNSAxMjcuNSAyNTUgMjU1VjE1M2M4NC4xNSAwIDE1MyA2OC44NSAxNTMgMTUzcy02OC44NSAxNTMtMTUzIDE1My0xNTMtNjguODUtMTUzLTE1M0g1MWMwIDExMi4yIDkxLjggMjA0IDIwNCAyMDRzMjA0LTkxLjggMjA0LTIwNC05MS44LTIwNC0yMDQtMjA0eiIgZmlsbD0iI0ZGRiIvPjwvc3ZnPg==)";
overlay.style.backgroundSize = "64px 64px";
overlay.style.top = 0;
overlay.style.bottom = 0;
overlay.style.display = "inline-block";
} else if (event.data == YT.PlayerState.PAUSED) {
overlay.style.backgroundImage = "url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEiIHdpZHRoPSIxNzA2LjY2NyIgaGVpZ2h0PSIxNzA2LjY2NyIgdmlld0JveD0iMCAwIDEyODAgMTI4MCI+PHBhdGggZD0iTTE1Ny42MzUgMi45ODRMMTI2MC45NzkgNjQwIDE1Ny42MzUgMTI3Ny4wMTZ6IiBmaWxsPSIjZmZmIi8+PC9zdmc+)";
overlay.style.backgroundSize = "40px 40px";
overlay.style.top = "40px";
overlay.style.bottom = "50px";
overlay.style.display = "inline-block";
} else if (event.data == YT.PlayerState.PLAYING) {
overlay.style.display = "none";
}
};
var player = new YT.Player(iframe, {
events: {
'onStateChange': onPlayerStateChange
}
});
wrapper.addEventListener("click", function() {
var playerState = player.getPlayerState();
if (playerState == YT.PlayerState.ENDED) {
player.seekTo(0);
} else if (playerState == YT.PlayerState.PAUSED) {
player.playVideo();
}
});
});
};
window.runOnce = true;
}
Jsfiddle: https://jsfiddle.net/pv75zjoh
I found out that if the youtube channel the video is from has less than (I don't know how many exactly but definitely more than 20 and less than 40) videos and the iframe youtube url has the rel=0 attribute, it won't show the related videos section at all.

I need help getting autoplay to work via [getElementById]

My code: https://jsfiddle.net/m656xw8s/24/
I've been trying to get autoplay to work, can someone show me what the correct code would be? Using the code I provided. Using [getElementById]
var player = document.getElementById('player').autoplay; document.getElementById('player').innerHTML = true;
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
var player = document.getElementById('player').autoplay;
document.getElementById('player').innerHTML = true;
var player = document.getElementById('player').volume='1.0';
var button = document.getElementById('playButton');
var player = document.getElementById('player');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>
Set the autoplay then load.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
Update:
document.getElementById('playButton').addEventListener('click', autoPlayToggle);
document.getElementById('autovolume_range').addEventListener('change', changeVol);
//Only getElementById once!
var player = document.getElementById("player");
var autoplaytext = document.getElementById("autoplay_text");
var autovolumetext = document.getElementById("autovolume_range");
//Boolean from localstorage to keep state of the player
var autoPlayOn = autoplaytext.value = (localStorage.getItem("keepAutoPlay") === "true");
var setVolumeOn = autovolumetext.value = parseFloat(localStorage.getItem("keepVolume"));
player.volume = setVolumeOn;
player.autoplay = autoPlayOn;
player.load();
//Force play if it dosen't autoplay after refresh
if (player.autoplay == true) {
player.play();
} else {
player.pause();
}
//Function
//When the user refreshes the page it will keep the autoplay state
function autoPlayToggle() {
if (player.paused) {
player.play();
player.autoplay = true;
} else {
player.pause();
player.autoplay = false;
}
//Show the state in a text box
autoplaytext.value = player.autoplay;
//Save updated state to your local disk
localStorage.setItem("keepAutoPlay", autoplaytext.value);
}
//Save state of volume
function changeVol() {
player.volume = this.value;
localStorage.setItem("keepVolume", this.value);
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;">
</button>
<audio id="player" style="display:none;" >
<source src='http://hi5.1980s.fm/;' type='audio/mpeg'/>
</audio>
AutoPlay: <input id="autoplay_text" />
AutoVolume: <input type="range" step="0.1" min="0.0" max="1.0" id="autovolume_range" />
https://jsfiddle.net/LeroyRon/dtnrdjd5/
You only need to add attribute auto play to your audio tag see the updated code below; Based on your code you are redeclaring player multiple times see the updated code below. Your auto play is triggered on button click based on your code, you may want to separate the javascript codes to the button and just trigger a method indicated on your button click event.
You will need to use removeAttribute to remove the autoplay from your audio element. I added the code on how to do it below.
//player declared outside of the audioPlay method to make it accessible inside the audioPlay method
var player = document.getElementById('player');
//auto play set outside playAudio method outside of the button click event method
player.setAttribute('autoplay', '');
//to set autoplay false uncomment the code below
//player.removeAttribute('autoplay');
//playAudio is triggered on button click event
function playAudio(){
player.setAttribute('volume', 1.0);
var button = document.getElementById('playButton');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
playAudio()">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>

Is there a way to use the Youtube API using less code?

I did some tests to find a way to play an embed video from youtube and it stops others videos of the page that is playing in the moment.
I reached the following code:
<!DOCTYPE html>
<html>
<head>
<title>Youtube players test</title>
<style type="text/css" >
li {
list-style: none;
margin-bottom: 10px;
}
</style>
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
</head>
<body>
<ul id="videos">
<li>Video1</li>
<iframe id="player1" class="video" type="text/html" width="400" height="225" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
frameborder="0" allowfullscreen></iframe>
<li>Video2</li>
<iframe id="player2" class="video" width="400" height="225" src="https://www.youtube.com/embed/3TAUnYZpMbA?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<li>Video3</li>
<iframe id="player3" class="video" width="400" height="225" src="https://www.youtube.com/embed/9U38GB2qVWA?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</div>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var primteste = document.getElementsByTagName('script')[0];
primteste.parentNode.insertBefore(tag, primteste);
var players = new Array();
function onYouTubeIframeAPIReady() {
players[0] = new YT.Player('player1', {
events: {
'onStateChange': onPlayer1StateChange
}
});
players[1] = new YT.Player('player2', {
events: {
'onStateChange': onPlayer2StateChange
}
});
players[2] = new YT.Player('player3', {
events: {
'onStateChange': onPlayer3StateChange
}
});
}
function onPlayer1StateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var x = 0;
for (i=0;i<3;i++) {
if (i == x) {
i++;
}
players[i].stopVideo();
}
}
}
function onPlayer2StateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var x = 1;
for (i=0;i<3;i++) {
if (i == x) {
i++;
}
players[i].stopVideo();
}
}
}
function onPlayer3StateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var x = 2;
for (i=0;i<3;i++) {
if (i == x) {
i++;
}
players[i].stopVideo();
}
}
}
</script>
</body>
</html>
The code above satisfies my initial intention of play/stop videos and here goes my question. I did with only three videos and It's not too great for three, but I have a page that has more than 20 embed videos and with the way I coded I will have to code the same for each one of the videos what it will take lines and lines. Because I thought a lot and I couldn't figure out a simpler way to do it.
Could someone gives me a light about this situation? Is there someone that sees a better way to do the same?
Thanks
Call the same onPlayerStateChange callback for all your players and stop all but the current player. To check if this is the current player, use event.target != players[i].
Here's your example with a few tweaks.
<!DOCTYPE html>
<html>
<head>
<title>Youtube players test</title>
<style type="text/css">
li {
list-style: none;
margin-bottom: 10px;
}
</style>
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
</head>
<body>
<ul id="videos">
<li>
<h4>Video 1</h4>
<iframe id="player1" class="video" width="400" height="225" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</li>
<li>
<h4>Video 2</h4>
<iframe id="player2" class="video" width="400" height="225" src="https://www.youtube.com/embed/3TAUnYZpMbA?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</li>
<li>
<h4>Video 3</h4>
<iframe id="player3" class="video" width="400" height="225" src="https://www.youtube.com/embed/9U38GB2qVWA?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</li>
</ul>
<script type="text/javascript">
// Insert youtube API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var primteste = document.getElementsByTagName('script')[0];
primteste.parentNode.insertBefore(tag, primteste);
var players = [];
function onYouTubeIframeAPIReady() {
// Populate 'players' with all the youtube iframes
var videoIframes = document.getElementsByClassName('video');
for(var i=0; i<videoIframes.length; i++){
players.push(
new YT.Player(videoIframes[i], { // here we can pass an iframe element or an id
events: {
'onStateChange': onPlayerStateChange
}
})
);
}
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
for (i=0; i<players.length; i++) {
// Stop all but the current player (the one that triggered the event)
if(players[i] != event.target){
players[i].stopVideo();
}
}
}
}
</script>
</body>
</html>
This code will automatically add new players to the players array as long as the iframe holding the player has the class .video.
You don't need to have an id for each iframe but I left them there just in case you're using them somewhere else.
function _getOnPlayerChangeHandler(playerIndex) {
return function (event) {
if (event.data === YT.PlayerState.PLAYING) {
var i;
for (i = 0; i < players.length; i++) {
if (i !== playerIndex) {
players[i].stopVideo();
}
}
}
};
}
function _createPlayer (selector, playerIndex) {
return new YT.Player(selector, {
onStateChange: _getOnPlayerChangeHandler(playerIndex)
});
}
players[0] = _createPlayer('player1', 0);
players[1] = _createPlayer('player2', 1);
players[2] = _createPlayer('player3', 2);
If you have more information about the player in the event object, you may not even have to create the handler from a factory like the one I've made.

Changing an element with js toggle

I made a function, so when you click on a link 'Play', div with black background changes to iframe video. It seems to be working fine. Problem is, that I want to add multiple play links with multiple videos. I don't know how to do it, so when you click on second play link, video changes from first video to second in the same place.
my code:
<script>
var toggle = function() {
var mydiv = document.getElementById('videoholder');document.getElementById("frame").src="http://www.youtube.com/embed/YuOBzWF0Aws";
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
PLAY<br>
<div style="width:560px; height:315px; background-color:#111111;">
<div id="videoholder" style="display:none;">
<iframe id="frame" width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>
</div></div>
You could try something like this.
<script>
function toggle(url) {
var mydiv = document.getElementById('videoholder');
document.getElementById("frame").src = url;
if (mydiv.style.display === 'block' || mydiv.style.display === '') {
mydiv.style.display = 'none';
} else {
mydiv.style.display = 'block'
}
}
</script>
PLAY 1<br>
PLAY 2<br>
<div style="width:560px; height:315px; background-color:#111111;">
<div id="videoholder" style="display:none;">
<iframe id="frame" width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>
</div></div>
You could use document.getElementById('frame').src='http://linktonewvideo.com';
Hope this helps!

How can I change play/button images in HTML5 audio?

I have the code of audio player. How can I change the picture of play/pause button when press?
<div class="onlineradio"><img src="images/Radio.jpg" alt="" />
<p><video id="yourAudio" width="0" height="0">
<source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
</video> <a id="audioControl" href="#"><img src="images/radioscalebutton.png" alt="" /></a></p>
</div>
<script>// <![CDATA[
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
// Update the Button
var pause = ctrl.innerHTML === 'pause!';
ctrl.innerHTML = pause ? 'pause' : 'play';
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
// Prevent Default Action
return false;
};
// ]]></script>
I have implemented a final working solution with custom audio controls (play and pause) with toggling state button. If something is not clear for you, please ask.
Here is the working solution and the JSFiddle:
var yourAudio = document.getElementById('yourAudio'),
ctrl = document.getElementById('audioControl'),
playButton = document.getElementById('play'),
pauseButton = document.getElementById('pause');
function toggleButton() {
if (playButton.style.display === 'none') {
playButton.style.display = 'block';
pauseButton.style.display = 'none';
} else {
playButton.style.display = 'none';
pauseButton.style.display = 'block';
}
}
ctrl.onclick = function () {
if (yourAudio.paused) {
yourAudio.play();
} else {
yourAudio.pause();
}
toggleButton();
// Prevent Default Action
return false;
};
#audioControl img {
width: 50px;
height: 50px;
}
#pause {
display: none;
}
<div class="onlineradio">
<img src="images/Radio.jpg" alt="" />
<p>
<audio id="yourAudio">
<source src='http://178.219.160.126:8000/stream.mp3' type='audio/mpeg' preload="auto" />
</audio>
<a id="audioControl" href="#">
<img src="http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons/glossy-black-3d-buttons-icons-media/002110-glossy-black-3d-button-icon-media-a-media22-arrow-forward1.png" id="play"/>
<img src="https://www.wisc-online.com/asset-repository/getfile?id=415&getType=view" id="pause"/>
</a>
</p>
</div>
You can download the images of controls and use refer to them locally.

Categories