Trigger overlay with button on other page - javascript

I am trying to control an overlay function in HTML with an external js file and a second HTML page where the buttons are on.
So far it works when the buttons are on the same page. But I can not trigger the overlay from page 1 on page 2.
So the streaming page is the page where the viewer will be able to look and interact.
<div id="overlay" onclick="turnOverLayOff()">
<div id="textContainer"><iframe src="https://docs.google.com/forms/d/e/1FAIpQLSe5NWLPhYiLqM2YIUPCsVk3RB5h660Wei9eDGyKUhMMIB4iZw/viewform?embedded=true" width="640" height="415" frameborder="0" marginheight="0" marginwidth="0">Laden…</iframe> </div>
</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/5A9v-n53LtI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<script src="overlay.js"></script>
Then the JS file is
function turnOverLayOn(){
document.getElementById('overlay').style.display = 'block';
}
function turnOverLayOff(){
document.getElementById('overlay').style.display = 'none';
}
The second page from where I want to control the streamingpage from :
<div id="overlay" onclick="turnOverLayOff()">
<div id="textContainer">Test tekst whatever </div>
</div>
<div>
<button onclick="turnOverLayOn()">Click here to turn ON </button>
</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/5A9v-n53LtI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<script src="overlay.js"></script>

As a means of signalling between the pages/tabs within the same browser you can use the BroadcastChannel api as mentioned in the comment above.
As demonstration - two basic HTML pages, both establish a connection to a common Broadcast Channel and one listens for messages from the other.
In the following the Video elements and iframes are commented out and replaced with simple text.
The getStyle function simply allows access programmatically to styles set on a named element and is used here to determine. The Javascript can be written to a single file and included in both pages as per the external.js...
Page 1 - the page being controlled
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Page 1: streamingpage</title>
<style>
#overlay{display:block}
</style>
</head>
<body>
<div id='overlay'>
<div id='textContainer'>
<!--<iframe src='https://docs.google.com/forms/d/e/1FAIpQLSe5NWLPhYiLqM2YIUPCsVk3RB5h660Wei9eDGyKUhMMIB4iZw/viewform?embedded=true' width='640' height='415' frameborder='0' marginheight='0' marginwidth='0'>Laden…</iframe>-->
IFRAME CONTENT - docs.google.com
</div>
</div>
<!--<iframe width='560' height='315' src='https://www.youtube.com/embed/5A9v-n53LtI' title='YouTube video player' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>-->
VIDEO-YouTUBE
<script>
const getStyle=(n,css)=>{
let style;
if( window.getComputedStyle ){
style = window.getComputedStyle( n, null ).getPropertyValue( css );
} else if( n.currentStyle ){
css = css.replace(/\-(\w)/g, function ( strMatch, p1 ){
return p1.toUpperCase();
});
style = n.currentStyle[ css ];
} else {
style='';
}
return style;
}
let oChan=new BroadcastChannel( 'tabs' );
oChan.addEventListener('message',(e)=>{
//inspect messages as they arrive
console.log( e.data );
let div=document.getElementById('overlay');
div.style.display=getStyle(div,'display')=='block' ? 'none' : 'block';
});
</script>
</body>
</html>
Page 2 - the page doing the controlling
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>page2: controller</title>
<style>
#overlay{display:block}
</style>
</head>
<body>
<div id='overlay'>
<div id='textContainer'>Test tekst whatever </div>
</div>
<div>
<button id='toggler'>Click here to turn ON</button>
</div>
<!--<iframe width='560' height='315' src='https://www.youtube.com/embed/5A9v-n53LtI' title='YouTube video player' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>-->
VIDEO-YouTUBE
<script>
const getStyle=(n,css)=>{
let style;
if( window.getComputedStyle ){
style = window.getComputedStyle( n, null ).getPropertyValue( css );
} else if( n.currentStyle ){
css = css.replace(/\-(\w)/g, function ( strMatch, p1 ){
return p1.toUpperCase();
});
style = n.currentStyle[ css ];
} else {
style='';
}
return style;
}
let oChan=new BroadcastChannel( 'tabs' );
sendmessage=function( data ){
oChan.postMessage( { 'data':data } )
};
let bttn=document.querySelector('button#toggler');
bttn.addEventListener('click',e=>{
let div=document.getElementById('overlay');
div.style.display=getStyle(div,'display')=='block' ? 'none' : 'block'
/*
send a message - the payload can be tailored to suit your needs and processed within the listener on page 1
this simply sends the `display` status of the local DIV but you can send whatever is meaningful/helpful.
*/
sendmessage( { state:getStyle(div,'display') } );
});
</script>
</body>
</html>

Related

How can I hide an iframe on click using JavaScript

There is a video playing when the user enters my website and when the video is clicked I would like to hide the iframe and show the menu page. Can someone help me with this?
This is my code:
$(document).ready(function(){
$("#menu-page").hide();
$("#SiteNav").hide();
$("#filecontainer").on("click",function(){
$("#menu-page").show();
$("#SiteNav").show();
$("#filecontainer").hide();
});
});
<div class="box" id="box">
<div class="main-video">
<iframe id="filecontainer" src="https://www.youtube.com/embed/NQokQxdFVqE?autoplay=1&mute=1&playlist=NQokQxdFVqE&loop=1&controls=0&showinfo=0&" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="1920" height="1042" frameborder="0">
</iframe>
</div>
<canvas id="canvas"></canvas>
</div>
You are not going to be able to detect a click in the iframe. You can add a layer over the page and detect that click and hide it that way.
$(".layer").on("click", function () {
$(".layer, #filecontainer").remove();
});
.layer{
position: absolute;
top: 0; left:0; height: 100%; width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="box">
<div class="main-video">
<iframe id="filecontainer" src="https://www.youtube.com/embed/NQokQxdFVqE?autoplay=1&mute=1&playlist=NQokQxdFVqE&loop=1&controls=0&showinfo=0&" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="1920" height="1042" frameborder="0">
</iframe>
</div>
<canvas id="canvas"></canvas>
</div>
<div class="layer"></div>

Show one i frame, hide another using vanilla JavaScript

If a user already has one video selected (using the drop-down), and they select another, I would like the first video to be replaced with the new video. Instead, how I have it set up right now, it is just appending the second video (or even third, if a third video is selected) after the first. How do I change my code to clear any current videos from the page before loading the new video?
<body>
<h1>Let's Meditate.</h1>
<select id="timer">
<option value="select" disabled selected>Select One...</option>
<option value="twenty">20 minutes</option>
<option value="fifteen">15 minutes</option>
<option value="ten">10 minutes</option>
<option value="five">5 minutes</option>
</select>
<button type="button" onclick="meditate();">Go!</button>
<button onclick="refresh();">Refresh</button>
<div class="videos">
<iframe id="twentyMinVid" width="560" height="315" src="https://www.youtube.com/embed/VjxGjDo1tWA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="fifteenMinVid" width="560" height="315" src="https://www.youtube.com/embed/aIIEI33EUqI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="tenMinVid" width="560" height="315" src="https://www.youtube.com/embed/Xl_B45DpMLU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="fiveMinVid" width="560" height="315" src="https://www.youtube.com/embed/3RxXiFgkxGc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<script>
function meditate() {
var timer = document.getElementById("timer").value;
if(timer == "twenty") {
document.getElementById("twentyMinVid").style.display = "block";
} else if(timer == "fifteen") {
document.getElementById("fifteenMinVid").style.display = "block";
} else if(timer == "ten") {
document.getElementById("tenMinVid").style.display = "block";
} else if(timer == "five") {
document.getElementById("fiveMinVid").style.display = "block";
} else {
document.querySelector(".videos").innerHTML = "Please select a time limit and click Go."
}
}
function refresh() {
location.reload();
}
</script>
</body>
Instead of making there display: block, try changing the iframe src.
<body>
<h1>Let's Meditate.</h1>
<select id="timer">
<option value="select" disabled selected>Select One...</option>
<option value="twenty">20 minutes</option>
<option value="fifteen">15 minutes</option>
<option value="ten">10 minutes</option>
<option value="five">5 minutes</option>
</select>
<button type="button" onclick="meditate();">Go!</button>
<button onclick="refresh();">Refresh</button>
<div class="videos">
<iframe id="iframe" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<script>
function meditate() {
var timer = document.getElementById("timer").value;
var iframe = document.getElementById("iframe");
if(timer == "twenty") {
iframe.src = "https://www.youtube.com/embed/VjxGjDo1tWA";
} else if(timer == "fifteen") {
iframe.src = "https://www.youtube.com/embed/aIIEI33EUqI";
} else if(timer == "ten") {
iframe.src = "https://www.youtube.com/embed/Xl_B45DpMLU";
} else if(timer == "five") {
iframe.src = "https://www.youtube.com/embed/3RxXiFgkxGc";
} else {
document.querySelector(".videos").innerHTML = "Please select a time limit and click Go."
}
}
function refresh() {
location.reload();
}
</script>
Here is my solution I modified your code a bit.
<body>
<h1>Let's Meditate.</h1>
<select id="timer">
<option value="select" disabled selected>Select One...</option>
<option value="twentyMinVid">20 minutes</option>
<option value="fifteenMinVid">15 minutes</option>
<option value="tenMinVid">10 minutes</option>
<option value="fiveMinVid">5 minutes</option>
</select>
<button type="button" onclick="meditate();">Go!</button>
<button onclick="refresh();">Refresh</button>
<div class="videos">
<iframe id="twentyMinVid" width="560" height="315" src="https://www.youtube.com/embed/VjxGjDo1tWA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="fifteenMinVid" width="560" height="315" src="https://www.youtube.com/embed/aIIEI33EUqI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="tenMinVid" width="560" height="315" src="https://www.youtube.com/embed/Xl_B45DpMLU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<iframe id="fiveMinVid" width="560" height="315" src="https://www.youtube.com/embed/3RxXiFgkxGc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<script>
function meditate() {
var timer = document.getElementById("timer").value;
if (timer === 'select') {
alert("Please select a time limit and click Go.");
return;
}
var options = document.getElementById("timer").options;
for (var i = 1; i < options.length; i++) {
if (options[i].value === timer) {
document.getElementById(timer).style.display = "block";
} else {
document.getElementById(options[i].value).style.display = "none";
}
}
}
function refresh() {
location.reload();
}
</script>
</body>
I tried to make it more generic so that if you add more option in dropdown then if dropdown value is same as frameId then no modification is needed in the logic to show/hide videos
link to fiddle
This is because you are not hiding the existing iframes when you display the new one.
For example, in this block:
if(timer == "twenty") {
document.getElementById("twentyMinVid").style.display = "block";
//Add code here for hiding the other divs
document.getElementById("fifteenMinVid").style.display = "none";
document.getElementById("tenMinVid").style.display = "none";
document.getElementById("fiveMinVid").style.display = "none";
}
....You need to do this same thing in other sections so that you are hiding other divs while you show the correct div.

I want to stop the YouTube video that is played when I press the Next or Previous button on BXSLIDER

I use this script code.
How can I modify my script?
<div class="video-slider">
<div>
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/-xmdWsgmeXk?playsinline=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div>
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/-xmdWsgmeXk?playsinline=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div>
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/-xmdWsgmeXk?playsinline=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
</div>
<script>
var slider = $(".video-slider").bxSlider({
pager : false
onSlideBefore : function($slideElement, oldIndex, newIndex) {
var src = $slideElement.find("iframe").attr("src");
console.log(src);
$("iframe").attr("src",'').attr("src",src);
}
});
</script>
The video address is for samples. Let me know if there is a good way.
I think you not write proper javascript for bxslider check my code.
<script>
var slider = $(".video-slider").bxSlider({
pager : false,
onSlideBefore : function($slideElement, oldIndex, newIndex) {
var src = $slideElement.find("iframe").attr("src");
console.log(src);
$("iframe").attr("src",'').attr("src",src);
}
});
</script>

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.

Youtube Video Player that plays video in same spot on button click

I am currently working on a project that is a navigation and a video player in the same div container.
https://i.stack.imgur.com/W49lY.png
https://i.stack.imgur.com/s89Oy.png
Once you click on one of the four boxes, another video will pop up and show in that same position.
Which approach should I go with? HTML/JavaScript?
I am totally new to JavaScript, so I know that this code is wrong, but this is what I have so far.
<div class="row" style="margin-left: auto;">
<div>
<button onclick="Word()">Word</button>
<button onclick="Excel()">Excel</button>
<button onclick="PowerPoint()">PowerPoint</button>
<button onclick="OneNote()">OneNote</button>
<br><br>
<video id="word" width="560" height="315" src="https://www.youtube.com/watch?v=S-nHYzK-BVg"></video>
<video id="excel" width="560" height="315" src="https://www.youtube.com/watch?v=S-nHYzK-BVg"></video>
<video id="powerpoint" width="560" height="315" src="https://www.youtube.com/watch?v=S-nHYzK-BVg"></video>
<video id="onenote" width="560" height="315" src="https://www.youtube.com/watch?v=S-nHYzK-BVg"></video>
</div>
<script>
var myVideo = document.getElementById("word");
function Word() {
if (myVideo.onClick)
myVideo.play();
else
myVideo.pause();
}
function Excel() {
myVideo.play();
else
myVideo.pause();
}
function PowerPoint() {
myVideo.play();
else
myVideo.pause();
}
function OneNote() {
myVideo.play();
else
myVideo.pause();
}
</script>
</div>
I would use one function called videoSelect() and change the HTML content of a div with the id of player when the button is clicked.
innerHTML is used to change the html content of an element.
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
(this.id) retrieves the button's id and passes it to your videoSelect function.
this.id = element
Full example here -> https://codepen.io/chaosmaths/pen/aKmOVm/
As a note the video URLs in your post were the same for all of the examples so I've changed the URLs to what I believe are the videos you wanted. If they aren't just change the URL in corresponding variable. You can also use the video tag instead of iframe. I just used that because it is what YouTube provides with their embed codes.
HTML
<div class="row">
<div id="options">
<button id="word" onclick="videoSelect(this.id)">Word</button>
<button id="excel" onclick="videoSelect(this.id)">Excel</button>
<button id="powerpoint" onclick="videoSelect(this.id)">PowerPoint</button>
<button id="onenote" onclick="videoSelect(this.id)">OneNote</button>
</div>
<div id="player"></div>
</div>
CSS
#options{
text-align: center;
}
#player{
text-align: center;
margin-top: 15px;
}
JS
var word = 'https://www.youtube.com/embed/S-nHYzK-BVg';
var excel = 'https://www.youtube.com/embed/rwbho0CgEAE';
var powerpoint = 'https://www.youtube.com/embed/XF34-Wu6qWU';
var onenote = 'https://www.youtube.com/embed/qN15XnU96vQ';
var player = document.getElementById('player');
function videoSelect(element){
if (element === "word"){
player.innerHTML = '<iframe width="560" height="315" src="' + word + '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
}
if (element === "excel"){
player.innerHTML = '<iframe width="560" height="315" src="' + excel + '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
}
if (element === "powerpoint"){
player.innerHTML = '<iframe width="560" height="315" src="' + powerpoint + '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
}
if (element === "onenote"){
player.innerHTML = '<iframe width="560" height="315" src="' + onenote + '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
}
}

Categories