How to make one button play several youtube videos in embedded iframes? - javascript

I have a few youtube videos embedded in a couple of iframes, and would like to start stop all the videos at once, using only one button. I've tried a few different methods, but just couldn't get it right.
Here is what I got.
main.html:
<!DOCTYPE html>
<html>
<head>
<title>YT Mosaic</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="container">
<div class="mosaic">
<iframe id="if1" src="https://www.youtube.com/embed/5mL-OkdM7Tc?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- TRT -->
<iframe id="if2" src="https://www.youtube.com/embed/9Auq9mYxFEE?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- SKY -->
<iframe id="if3" src="https://www.youtube.com/embed/VBTdNwm5CDY?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Global News -->
<iframe id="if4" src="https://www.youtube.com/embed/ntmPIzlkcJk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- Euronews -->
<iframe id="if5" src="https://www.youtube.com/embed/GE_SfNVNyqk?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- DW -->
<iframe id="if6" src="https://www.youtube.com/embed/h3MuIUNCCzI?cc_load_policy=3&autoplay=0&mute=1&enablejsapi=1" frameborder="0" allowfullscreen></iframe> <!-- F24 -->
</div>
<button onclick="iframe1play(); return false;">⏯️</button>
<button onclick="stop();">⏹</button>
<button onclick="playAll();">▶▶ Play All</button>
</div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var ifa = []; // array of iframe id's
var ifos = []; // array of iframe YT objects for use elsewhere
// For each iframe you find, add its ID to the ifa array
var iframes = document.querySelectorAll("div.mosaic iframe");
iframes.forEach(function(iframe) {
ifa.push(iframe.id);
});
console.log('[LOG] iframe array:', ifa)
// Array(6) [ "if1", "if2", "if3", "if4", "if5", "if6" ]
// Once the YouTube API is ready, for each iframeId in your array,
// create a new YT player and give it the onReady event.
function onYouTubeIframeAPIReady() {
ifa.forEach(function(iframeId) {
var player = new YT.Player(iframeId, {
events: {
'onReady': onPlayerReady,
}
});
});
}
function onPlayerReady(event) {
var ifo = event.target;
ifos.push(ifo); // Push current iframe object to ifo array
ifos.forEach(function(j) {
j.setVolume(30);
j.playVideo();
j.unMute();
});
}
var player;
// WARNING this need to be commented out as it interferes with the other version.
function onYouTubeIframeAPIReady() {
player = new YT.Player('if1', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000); // wait 6 s. before stopping player
done = true;
}
}
function catchError(event) {
if (event.data == 2) console.log("[LOG] Error: The request contains an invalid parameter value.");
if (event.data == 5) console.log("[LOG] Error: content cannot be played in an HTML5 player.");
if (event.data == 100) console.log("[LOG] Error: Video doesn't exists (or has been removed)!");
if (event.data == 101) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
if (event.data == 150) console.log("[LOG] Error: Not allowed to be played in an embedded player.");
// This should never happen!
console.log("Error:\n", event);
}
// This was a test, not working, trying to use:
// onload="p1=new YT.Player(this);">
function playAll() {
var ifs = [p1,p2,p3,p4,p5,p6];
for(var i=0; i<ifs.length; i++) {
console.log("Try to Play: ", toString(ifs[i]));
ifs[i].playVideo();
}
}
function play() {
//player.unMute();
player.playVideo();
//show_video_url();
}
function pause() { player.pauseVideo(); }
function stop() { player.stopVideo(); }
function stopVideo() { player.stopVideo(); }
function mute() { player.unMute(); }
function iframe1play() {
if (player.getPlayerState() == YT.PlayerState.PLAYING) {
player.pauseVideo();
document.getElementById("if1").style.opacity = "0.7";
} else {
player.playVideo();
document.getElementById("if1").style.opacity = "1";
}
}
</script>
</body>
<footer>FTSE</footer>
</html>
and here is the CSS file main.css:
body {
background-color: #404040;
color: lightgrey;
margin: 0;
padding: 1em;
/*height: 100vh;*/
box-sizing: border-box;
}
.container {
max-width: 1100px;
/* width: 100%;*/
border: 1px solid black;
padding: 10px;
}
.mosaic {
display: grid;
/* Setup a 2x3 frame: */
/* fr is a fractional unit and 1fr is for 1 part of the available space */
grid-template-columns: 1fr 1fr;
grid-template-rows: 50% 50% 50%;
/*grid-template-rows: 1fr 1fr 1fr;*/
max-width: 1100px; /* 100% */
max-height: 100%; /* 100% */
/*aspect-ratio: 16/9;*/ /* 16/9 */
/* margin: auto; */ /* auto */
margin-bottom: 1em; /* 1em */
/*padding: 2em; */
gap: 5px; /* 1em */
}
iframe {
/* iframe width="560" height="315" */
display: block;
width: 100%;
height: 100%;
aspect-ratio: 16/9; /* */
/*min-width: 350px;*/ /* 350px */
/*min-height: 200px;*/ /* 200px */
background: gray; /* yellow */
border: 1px solid black; /* border: solid red */
margin: 0px; /* */
}
How can I use the iframe id= tag to start all iframe videos using one button?
preferably using JS without additional libraries, such as jQuery.
JSfiddle code

You can use Youtube's IFrame Player API. They have a great documentation here https://developers.google.com/youtube/iframe_api_reference
You can basically control all youtube embed videos by generating it through their API.
A working sample would be down below:
<body>
<div id="container">
<div id="player-5mL-OkdM7Tc"></div> <!-- TRT -->
<div id="player-9Auq9mYxFEE"></div> <!-- SKY -->
<div id="player-VBTdNwm5CDY"></div> <!-- Global News -->
<div id="player-ntmPIzlkcJk"></div> <!-- Euronews -->
<div id="player-GE_SfNVNyqk"></div> <!-- DW -->
<div id="player-h3MuIUNCCzI"></div> <!-- F24 -->
</div>
<button onclick="play()">
Play All
</button>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="main.js" async defer></script>
</body>
let playersObjs = [];
window.onYouTubeIframeAPIReady = () => {
const playerContainers = document.querySelectorAll('div[id^="player"]');
playerContainers.forEach((container) => {
const videoId = container.id.slice(7);
playersObjs.push(new YT.Player(container.id, {
height: '200',
width: '100',
videoId,
playerVars: {
'playsinline': 1
}
}))
})
}
const play = () => {
playersObjs.forEach((player) => {
player.playVideo();
})
}

Related

How can I disable a JQuery function by clicking on a button, but keep it on by default?

I'm creation a video player which redirects to another video page when the video is over.
I want to add a 'Turn Auto Play Off Button' to disable the redirection script.
How can I do that?
My code:
<video src="http://www.w3schools.com/html/movie.mp4" id="myVideo" controls>
video not supported
</video>
<button id="turnOfAutoPlay">Turn Of Auto Play</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myVideo").bind('ended', function() {
setTimeout(function() {
location.href = "http://www.localhost.com";
}, 3000)
});
});
</script>
You could remove the listener that fires at the end using unbind()
For jQuery < 1.7 use bind()/unbind()
$('#turnOfAutoPlay').click(function() {
$('#myVideo').unbind('ended');
})
Note: With jQuery 3.0 and up .bind()/.unbind() is deprecated. Use
on()/off()
function videoEndedHandler () {
setTimeout(function() {
location.href = "http://www.localhost.com";
}, 3000)
}
$(document).ready(function() {
document.getElementId("#myVideo").addEventListener('ended', videoEndedHandler);
});
$('#turnOfAutoPlay').on('click', function() {
document.getElementId('#myVideo').removeEventListener('ended', videoEndedHandler);
})
Use global variable for setTimeout function and on click of your "Turn Auto Play Off Button" call clearTimeout
Sample code:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Edit: here you go
<video src="http://www.w3schools.com/html/movie.mp4" id="myVideo" controls>
video not supported
</video>
<button id="turnOfAutoPlay" onclick="myStopFunction()">Turn Of Auto Play</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var myVar;
$(document).ready(function() {
$("#myVideo").bind('ended', function() {
myVar = setTimeout(function() {
location.href = "http://www.localhost.com";
}, 3000)
});
});
function myStopFunction() {
clearTimeout(myVar);
}
</script>
I modified my code a bit with the help of above discussions, but I think it's lil bulky 😅😅, But it works...
My Code:
const autoplayCheckbox = document.getElementById('autoplayCheckbox');
const video = document.getElementById('myVideo');
var myVar;
function videoEndedHandler () {
myVar = setTimeout(function() {
location.href = "http://www.localhost.com";
}, 10000)
}
//By default autoplay is on.
$(document).ready(function() {
video.addEventListener('ended', videoEndedHandler);
});
autoplayCheckbox.addEventListener('change', function() {
if (this.checked) {
//if autoplay is on
document.getElementById("demo").innerHTML = "Autoplay: On";
$(document).ready(function() {
video.addEventListener('ended', videoEndedHandler);
});
} else {
//if autoplay is off
document.getElementById("demo").innerHTML = "Autoplay: Off";
video.removeEventListener('ended', videoEndedHandler);
}
});
function myStopFunction() {
clearTimeout(myVar);
document.getElementById("autoplayCheckbox").checked = false;
document.getElementById("demo").innerHTML = "Autoplay: Off";
}
* {
box-sizing: border-box;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
transition: background 0.4s linear;
background-color: #8ecae6;
font-family: 'oswald';
}
.checkbox {
opacity: 0;
position: absolute;
}
.checkbox:checked + .label .ball {
transform: translateX(23px);
}
.label {
background-color: #111;
display: flex;
align-items: center;
justify-content: space-between;
border-radius: 50px;
position: relative;
padding: 5px;
height: 26px;
width: 50px;
transform-scale(2.2);
}
.ball {
background-color: #fff;
border-radius: 50%;
position: absolute;
top: 2px;
left: 2px;
height: 22px;
width: 22px;
transition: transform 0.3s linear;
}
<br/><br/><video src="http://www.w3schools.com/html/movie.mp4" id="myVideo" controls>
video not supported
</video>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- partial:index.partial.html -->
<div>
<input type="checkbox" class="checkbox" id="autoplayCheckbox" checked="checked">
<label for="autoplayCheckbox" class="label">
<div class="ball"></div>
</label>
</div>
<p id="demo">Autoplay: On</p>
<button id="turnOfAutoPlay" onclick="myStopFunction()">Turn Of Auto Play</button><br/><br/>
The Turn Of Autoplay button only works when 10sec Timeout function is going on..
I added that button because in the main project it also works as a button to dismiss the modal Have a look
Can i minify it??

YouTube API does not work in Google Chrome

I am making a website where a video has to be shown, this video to hide the recommended videos and prevent the URL from being obtained, I established a layer in front of the video, then I put a div in front of the iframe so that it would not let interact with the video interface.
The problem I have is that when testing with FIREFOX it works correctly, when testing with Google Chrome, it does not work for me, the screen remains plastered, That is, when displaying the page, the embedded video has a layer as an image and a button, I do this with PlayerState.UNSTARTED, and adding the corresponding class to show me said image, playerWrap.classList.add ("ended") ;.
I have no error in the console.
However, if I try the same with Google Chrome, when displaying the page, the embedded video only keeps the image layer, it does not let me click to play video.
any idea why this happens?
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="shortcut icon" href="imgs/icon/favicon.ico">
<style>
.hytPlayerWrap{
display:inline-block;
position:relative
}
.hytPlayerWrap.unstarted::after{
content:"";position:absolute;
top:0;
left:0;
bottom:0;
right:0;
cursor:pointer;
background-repeat:no-repeat;
background-position:center;
background-size:64px 64px;
background-image:url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiB2aWV3Qm94PSIwIDAgNTEwIDUxMCI+PHBhdGggZD0iTTI1NSAxMDJWMEwxMjcuNSAxMjcuNSAyNTUgMjU1VjE1M2M4NC4xNSAwIDE1MyA2OC44NSAxNTMgMTUzcy02OC44NSAxNTMtMTUzIDE1My0xNTMtNjguODUtMTUzLTE1M0g1MWMwIDExMi4yIDkxLjggMjA0IDIwNCAyMDRzMjA0LTkxLjggMjA0LTIwNC05MS44LTIwNC0yMDQtMjA0eiIgZmlsbD0iI0ZGRiIvPjwvc3ZnPg==)
}
.hytPlayerWrap.ended::after{
content:"";position:absolute;
top:0;
left:0;
bottom:0;
right:0;
cursor:pointer;
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-repeat:no-repeat;
background-position:center;
background-size:40px 40px;
background-image:url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEiIHdpZHRoPSIxNzA2LjY2NyIgaGVpZ2h0PSIxNzA2LjY2NyIgdmlld0JveD0iMCAwIDEyODAgMTI4MCI+PHBhdGggZD0iTTE1Ny42MzUgMi45ODRMMTI2MC45NzkgNjQwIDE1Ny42MzUgMTI3Ny4wMTZ6IiBmaWxsPSIjZmZmIi8+PC9zdmc+)}
.hytPlayerWrap.ended iframe,
.hytPlayerWrap.paused iframe{
visibility: hidden;
background-repeat: no-repeat;
}
.hytPlayerWrap {
background-position: center;
background-repeat: no-repeat;
}
.yt-cover{
position: absolute;
top: 0;
bottom:0;
right:0;
left:0;
z-index:1000;
}
</style>
<title>Congreso Intessrnacional 2021</title>
</head>
<body id="plenario">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<br><br><br><br>
<div class="row">
<div class="col-2"> </div>
<div class="col-8 text-center">
<div class="hytPlayerWrapOuter" >
<div class="hytPlayerWrap" style="background-image:url(imgs/intro22.png)">
<iframe id="yt-frame" width="605" height="340" src="https://www.youtube.com/embed/6XYzWjixpwE?rel=0&autoplay=1&mute=0&control=1&enablejsapi=1&autoplay=0&fs=0&rel=0&modestbranding=1&showinfo=0&iv_load_policy=3&modestbranding=1&nologo=1" frameborder="0" ></iframe>
<div class="yt-cover"></div>
</div>
</div>
</div>
</div>
<div class="col-2"> </div>
</div>
</div>
<div class="seccion-regresar-plenario">
<a class="boton-regresar-plenario" href="salones.php"></a>
</div>
</div>
</div>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/utiles.js"></script>
<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.UNSTARTED) {
playerWrap.classList.add("ended");
}
else 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.UNSTARTED) {
player.playVideo();
}
else 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>
</body>
</html>

How to Open a link (web page) in fullscreen mode, javascript?

simply I need to open a new page in fullscreen.
So, users press a button and then a video (hidden on main page) is open in fullscreen and start to play. When user press button to close fullscreen or press "esc" key, video will pause, fullscreen is closed and iframe is not visible...
I'm try to get this demo works, but with no results.
Also I can make it works only if I open only the video element, not iframe...
const fullscreen = document.querySelector('.playnow');
const video = document.querySelector('#myvideo');
fullscreen.addEventListener('click', toggleFullScreen);
// Create fullscreen video button
function toggleFullScreen() {
if(video.requestFullScreen){
video.requestFullScreen();
} else if(video.webkitRequestFullScreen){
video.webkitRequestFullScreen();
} else if(video.mozRequestFullScreen){
video.mozRequestFullScreen();
};
video.classList.remove("d-none");
}
body{
margin:0;
padding:0;
}
.video-container{
width:100%;
height:100vh;
margin: 0 auto;
position:relative;
background-image: url(https://images.unsplash.com/photo-1616485828923-2640a1ee48b4?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=3150&q=80);
background-repeat:no-repeat;
background-size:cover;
background-position: center;
}
#myvideo{
}
.d-none{
display:none;
}
<div class="video-container">
<button class="playnow">Open Video in Fullscreen Mode</button>
<video width="100%" autoplay id="myvideo" class="d-none">
<source src="//d2zihajmogu5jn.cloudfront.net/big-buck-bunny/master.m3u8" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
I've tried:
https://gomakethings.com/how-to-play-a-video-in-full-screen-mode-when-its-thumbnail-is-clicked-with-vanilla-js/ (better demo, but video still visible after fullscreen is closed...)
https://www.hongkiat.com/blog/html5-fullscreen-api/
But no appreciable results.
Thank you, Luca
I think you can try something like that.
const btn = document.querySelector('button')
const screenWidth = window.screen.availWidth;
const screenHeight = window.screen.availHeight
function openFullscreenWindow() {
window.open('https://github.com', '_blank', `width=${screenWidth},height=${screenHeight}`)
}
btn.addEventListener('click', openFullscreenWindow)
<button>Open fullscreen</button>
Maybe a found a solution reading this post on medium: https://medium.com/#roidescruzlara/controlling-the-full-screen-mode-cda0fae4c4f2
And now I can use it as I need.
Thank you so much.
var currentWindowHeight = window.innerHeight;
var element = document.getElementById("container");
var btn = document.getElementById("btn-screen-mode");
var film = document.getElementById("film");
var isFullScreen = false;
window.addEventListener("keydown", useCustomFullScreen.bind(this));
window.addEventListener("resize", isExitingFullScreen.bind(this));
/**
* Gets available exitFullscreen method
*/
function getRequestFullScreen() {
return (
element.requestFullscreen ||
element["mozRequestFullscreen"] ||
element["msRequestFullscreen"] ||
element["webkitRequestFullscreen"]
);
}
/**
* Gets available requestFullscreen method
*/
function getExitFullscreen() {
return (
document["webkitExitFullscreen"] ||
document["msExitFullscreen"] ||
document.exitFullscreen
);
}
/**
* Prevents browser to enter the default fullscreen mode and uses the custom fullscreen method
*/
function useCustomFullScreen(event) {
if (event.key === "F11") {
event.preventDefault();
toggleFullScreen();
}
}
/**
* Detects if the browser is exiting fullscreen mode when window resize
*/
function isExitingFullScreen() {
if (isFullScreen && currentWindowHeight >= window.innerHeight) {
isFullScreen = false;
currentWindowHeight = window.innerHeight;
// Do your full screen mode stuff
updateBtn();
}
}
/**
* Update button appearance according to the current screen mode
*/
function updateBtn() {
if (isFullScreen) {
btn.classList.remove("enter-fullscreen");
btn.classList.add("exit-fullscreen");
element.classList.remove("d-none");
film.play();
return;
}
btn.classList.remove("exit-fullscreen");
btn.classList.add("enter-fullscreen");
element.classList.add("d-none");
film.pause();
}
/**
* Toggles the fullscreen mode using available fullscreen API
*/
function toggleFullScreen() {
if (!isFullScreen && getRequestFullScreen()) {
getRequestFullScreen().call(element);
} else {
getExitFullscreen().call(document);
}
currentWindowHeight = window.innerHeight;
isFullScreen = !isFullScreen;
// Do your full screen mode stuff
updateBtn();
}
.container {
position: relative;
width: 100%;
height: 100%;
}
#container video {
width: 100%;
height: 100%;
object-fit: cover;
}
.intro{
width:100%;
height:100vh;
}
.intro video{
max-width:100%;
height:auto;
object-fit: cover;
}
.d-none{
display:none;
}
#btn-screen-mode {
width: 30px;
height: 30px;
border-radius: 5px;
border: 0;
padding: 0;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.enter-fullscreen {
position: absolute;
top:0;bottom:0;left:0;right:0;
margin: auto;
z-index:2322333;
background-image: url(https://cdn.icon-icons.com/icons2/1674/PNG/512/expand_111060.png);
}
.exit-fullscreen {
border: 2px solid #000;
position: absolute;
top:20px;
right:20px;
z-index:2322333;
background-image: url(https://cdn.icon-icons.com/icons2/1673/PNG/512/collapseoutline_110793.png);
}
<div class="intro">
<button id="btn-screen-mode" class="enter-fullscreen" onclick="toggleFullScreen()"></button>
<video autoplay loop muted playsinline="true" webkit-playsinline="true">
<source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" type="video/mp4">
</video>
</div>
<div class="container d-none" id="container">
<button id="btn-screen-mode" class="exit-fullscreen" onclick="toggleFullScreen()"></button>
<video loop playsinline="true" webkit-playsinline="true" id="film">
<source src="//d2zihajmogu5jn.cloudfront.net/big-buck-bunny/master.m3u8" type="video/mp4">
</video>
</div>

Turn background video (ambient video) into a playable video on button click

I have created an iframe by taking advantage of YouTube's API.
On page load, the ambient video is set to autoplay with no sound. However, on top of the div which contains the iframe, I have a button.
On this button click, I want the video to reset (start from the beginning) with the YouTube controls and sound on - similar to the one in the hero here: https://www.hugeinc.com/work.
Wondering how I would go about this? Would it involve creating another iframe?
Not looking to do this as a modal pop-up
Code:
// Load IFrame Player API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Creating iframe
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'jagIsKF8oVA',
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1,
'rel': 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// Calls function
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
// if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
// done = true;
// }
}
function stopVideo() {
// player.stopVideo();
}
<!-- THIS IS IN home.php-->
<button>Click me</button>
<!-- THIS IS IN hero.php -->
<section id="videoHero" class="hero hero--video">
<div class="hero__container--teaser">
<!-- Where the iframe is stored-->
<div id="player"></div>
</div>
</section>
Not looking to do this as a modal pop-up. Similar to the functionality here: https://www.hugeinc.com/work (play button on hero is clicked, video resets and plays from the start with controls at the bottom).
I used another iframe because there is no method to change the controls display you may check https://developers.google.com/youtube/iframe_api_reference for more information or you can do console.log(player) and ckeck all the methods.
I used
contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
to stop the iframe and
contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
to restart it also for this two line of code to work I added &enablejsapi=1 to the iframe src
also I used the YouTube Player API for the muted video so that it will loop whiteout refresh (in case of not using the YouTube Player API for the video to loop you need to add to the src of the iframe playlist=videoId&loop=1 and this will make the iframe refresh when the video end)
I haven't added showinfo=0 to the muted video because it is deprecated and will be ignored after September 25, 2018.
you may check https://developers.google.com/youtube/player_parameters#showinfo for more info
Lastly the snippet doesn't work . you need to make local html file or delete sandbox from the sinppet iframe then click on Run code snippet a second time
var modalTeaser = document.getElementById('hero__container--teaser');
var btn = document.getElementById("myBtn");
var iframe = document.getElementById("iframe");
var span = document.getElementsByClassName("close")[0];
var videoId = '88xPxULx-II';
var tag = document.createElement('script');
tag.id = 'iframe-demo';
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('iframe', {
videoId: videoId,
playerVars: {
'autoplay': 1,
'controls': 0,
'mute': 1,
'loop': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data === YT.PlayerState.ENDED) {
player.playVideo();
}
}
var video = document.createElement('iframe');
video.className = "ply";
modalTeaser.prepend(video);
video.style.display = 'none';
video.src = "https://www.youtube.com/embed/"+videoId+"?enablejsapi=1";
video.setAttribute('frameborder', "0");
btn.onclick = function() {
iframe.style.display = "none";
video.style.display = "block";
btn.style.display = "none";
span.style.display = "block";
video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*')
}
span.onclick = function() {
iframe.style.display = "block";
video.style.display = "none";
btn.style.display = "block";
span.style.display = "none";
video.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
}
body {
margin: 0;
}
.close{
z-index: 10;
position: relative;
display: none;
}
.ply{
z-index: 2 !important;
}
#videoHero {
position: relative;
padding-bottom: calc((544 / 1280) * 100%);
background-color: rgba(255, 0, 0, .1)
}
.hero__container--teaser {
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
.modal{
width: 80%;
height: 80%;
background-color: black;
}
/* Having the following on the iframe moves the iframe out of the div (and visual). Not having them puts
the iframe in the div, but not full width not height of #videoHero*/
#player,
iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -10;
}
#myBtn {
position: absolute;
top: 80px;
left: 300px;
z-index: 10;
width: 100px;
height: 100px;
background-color: red;
}
.modal {
display: none;
position: fixed;
z-index: 122;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.modal-content {
z-index: 400;
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
<section id="videoHero" class="hero hero--video">
<button type="button" class="close" data-dismiss="modal" aria- label="Close">
<span aria-hidden="true">×</span>
</button>
<div id="hero__container--teaser" class="hero__container--teaser">
<!-- #player is where the iframe is-->
<div id="iframe" ></div>
</div>
<button id="myBtn">Start video</button>
</section>

How to play/start vimeo video after clicking on an image?

I have some code, that works good with youtube videos, but I need the same effect with vimeo videos, wondering how to do this, any suggestions? Need replace youtube discription by vimeo but I don't know how to do this.
P.S Sorry for my English...
<style type="text/css">
#head {
background-color:transparent;
width:100%;
}
#container {
cursor:pointer;
width:520px;
height:380px;
}
.inactive-state {
background-repeat: no-repeat;
background-size: 100%;
background-image: url();
}
.hover-state {
background-image: url();
}
</style>
<section id="head">
<div id="container" class="click-to-play-video inactive-state">
<div id="player" class="home-player"></div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$("#container").mouseenter(function () {
$(this).addClass('hover-state');
}).mouseleave(function () {
$(this).removeClass('hover-state');
});
$("#container.click-to-play-video").click(function () {
$('#head').css({ "background-color": "transparent" });
player = new YT.Player('player', {
width: '520',
height: '300',
videoId: 'qlEUrEVqDbo',
playerVars: { 'autoplay': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
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 onPlayerReady(event) {
//event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
player.destroy();
$('#head').css({ "background-color": "transparent" });
}
}
</script>
In it's most simple form, you'll want something like this. Just remove the image and append the iframe, with autoplay on.
$('.vimeo-img').click(function (event) {
var $this = $(this),
$parent = $this.parent();
$this.remove();
$parent().append('<iframe src="..." autoplay="true"></iframe>');
})

Categories

Resources