Fire an event on play of youtube iframe embed - javascript

I need to fire an event on play of a youtube iframe. So when the play button is pressed I need to call a function to hide the span.module-strip
I've tried this but maybe I'm going down the wrong path?
$("#home-latest-vid")[0].onplay = function() {
alert('hi');
};
HTML:
<div class="module module-home-video">
<span class="module-strip">Latest Product Video</span>
<iframe id="video" src="http://www.youtube.com/embed/RWeFOe2Cs4k?hd=1&rel=0&autohide=1&showinfo=0&enablejsapi=1" frameborder="0" width="640" height="360"></iframe>
</div>

DEMO: https://so.lucafilosofi.com/fire-an-event-on-play-of-youtube-iframe-embed/
<script src="https://www.youtube.com/iframe_api"></script>
<div class="module module-home-video">
<span class="module-strip">Latest Product Video</span>
<div id="video"></div>
</div>
<script>
var player, playing = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video', {
height: '360',
width: '640',
videoId: 'RWeFOe2Cs4k',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
alert('video started');
playing = true;
}
else if(event.data == YT.PlayerState.PAUSED){
alert('video paused');
playing = false;
}
}
</script>

You should be able to use the youtube javascript api, doing something like this:
var ytplayer = null;
// event that will be fired when the player is fully loaded
function onYouTubePlayerReady(pid) {
ytplayer = document.getElementById("ytplayer");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
// event that will be fired when the state of the player changes
function onPlayerStateChange(state) {
// check if it's playing
if(state == 1) {
// is playing
}
}
To load your video in a embedded player you would use the following url:
http://www.youtube.com/v/RWeFOe2Cs4k?version=3&enablejsapi=1
I also think you should be able to add the iframe directly like this:
<iframe id="ytplayer" type="text/html" width="640" height="360"
src="https://www.youtube.com/embed/RWeFOe2Cs4k?enablejsapi=1"
frameborder="0" allowfullscreen>
Reference: Youtube Javascript Player API

player.getPlayerState():Number Returns the state of the player.
https://developers.google.com/youtube/iframe_api_reference
/*
* player.getPlayerState():Number
*
* -1 – unstarted
* 0 – ended
* 1 – playing
* 2 – paused
* 3 – buffering
* 5 – video cued
*
*/
function checkIfPlaying(){
var playerStatus = player.getPlayerState();
return playerStatus == 1;
}

Related

youtube autoplay is not working

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

How to control a youtube iframe sound through javascript/jquery event

I am looking to catch the sound provided in an iframe youtube video in order to stop/play it through a sound button.
Since the volume opt does not work anymore I tried this.
function toggleSound() {
var soundElem = document.getElementbyId("frame1") // also tried with iframe.getElementbyId()
soundElem.volume = 0.3
if (soundElem.paused) {
soundElem.play()
}
else
soundElem.pause()
}
//my yt video
<iframe id=iframe1 src="//www.youtube.com/embed/YOUTUBECODE?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
// my volume btn
<div class=volume-button onmousedown=toggleSound();>
I can't get the youtube audio and the youtubeAPI does not provide me an event with an external button ?
Kind Regards,
With the IFrame Player API you can use the mute method to mute the sound with an external event:
var player
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: 1280,
height: 720,
videoId: 'M7lc1UVf-VE'
})
}
function toggleSound() {
if (player.isMuted()) {
player.unMute()
} else {
player.mute()
}
}

Lazy Load youtube video from iframe API

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

Possible to add an onclick event to a YouTube iframe?

I've got a site with an HTML5 audio player and embedded YouTube music videos. I'd like to make it so that when the user clicks on a YouTube video to play it the music will stop. Wrapping the iframe in
<div id='vidWrapper' onclick='pauseAudio()'>YT stuff</div>
works for the sliver of pixels outside of the iframe, but not when you click on the actual video. Anyone have any ideas?
You should use the YouTube IFrame API. Add an event listener for onStateChange to get notified when the player's state changes. See the sample code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
<div id='vidWrapper'>
<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="ytplayer"></div>
</div>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
pauseAudio();
}
}
}
});
}
function pauseAudio() {
...
}
</script>
</body>
</html>
//More Refined Way to answer this question would be --
//HTML code----
<!DOCTYPE html>
<html>
<body>
<div id='vidWrapper'>
//your iframe tag goes here.
<iframe id="video-id-first" src="https://www.youtube.com/embed/nNlEiuqiKAk?enablejsapi=1&origin=http%3A%2F%2F3.7.232.244" gesture="media" allow="encrypted-media" allowfullscreen="" data-gtm-yt-inspected-53610233_3="true" width="560" height="400" frameborder="0"></iframe>
</div>
</body>
</html>
//JS code ----
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;
var width = document.getElementById("video-id-first").getAttribute("width");
var height = document.getElementById("video-id-first").getAttribute("height");
var src = document.getElementById("video-id-first").getAttribute("src");
//splitting to get the videoId from src.
var partsArr = src.split("/");
var videoSource = partsArr[partsArr.length -1 ].split("?");
var videoId = videoSource[videoSource.length -2 ];
function onYouTubeIframeAPIReady() {
player = new YT.Player('vidWrapper', {
height:height,
width: width,
videoId: videoId,
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
startVideo();
}
if (event.data == YT.PlayerState.PAUSED) {
stopVideo();
}
}
}
});
}
function startVideo() {
//write your functionality here.
alert('Video Started');
}
function stopVideo() {
//write your functionality here.
alert('Video Paused');
}

Stop flexslider when video is playing

I am using flexslider plugin in order to show a picture and video. The slides are changed automatically and it's fine with me. The problem is, that when user plays the video (iframe from youtube), flexslider continues to change slides.
I've checked the documentation and found pauseOnHover, which kinda does the trick, but i'd much rather prefer it to pause when video is started and continue when video is paused/has ended. Any suggestions on how to handle this?
EDIT
Here's the div where iframe is opened:
<div class="span6 animated fadeInLeftBig" id="main-media">
<iframe width="560" height="315" src="https://www.youtube.com/embed/someID?version=3&enablejsapi=1" frameborder="0" allowfullscreen id="iframe-id"></iframe>
</div>
The best way to solve this, is to use YouTube API, somethnig like this:
//Implement Youtube API
(function(){
var s = document.createElement("script");
s.src = "http://www.youtube.com/player_api"; /* Load Player API*/
var before = document.getElementsByTagName("script")[0];
before.parentNode.insertBefore(s, before);
})();
var YT_ready=(function(){var b=[],c=false;return function(a,d){if(a===true){c=true;while(b.length){b.shift()()}}else if(typeof a=="function"){if(c)a();else b[d?"unshift":"push"](a)}}})();
YT_ready(function() {
(function($) {
var frameID = "yourIframeID"
var player = new YT.Player(frameID, {
events: {
"onStateChange": function(event) {
if (event.data == 1 || event.data == 3) {
$('.flexslider').flexslider("pause");
}
else if (event.data == 0 || event.data == 2 || event.data == 5) {
$('.flexslider').flexslider("play");
}
}
}
});
});
})(jQuery);
function onYouTubePlayerAPIReady() {
YT_ready(true)
}

Categories