Stop flexslider when video is playing - javascript

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)
}

Related

My livefeed reloads every 30 seconds. How stop refresh when playing video?

I've made a live-feed for my website. Every 30 seconds the content reloads. But now I have a problem. When I'm adding an embedded video (from Youtube) or an HTML5 <video>, I can't play the video completely because of the reload. Is it possible to stop the auto reload when the video is playing, and restart the reload when the video has stopped?
This is what I use for the reload:
$(document).ready(function() {
$("#updates").load("updates.php");
var refreshId = setInterval(function() {
$("#updates").load('updates.php' + '?randval=' + Math.random());
}, 30000);
$.ajaxSetup({
cache: false
});
});
You can video my live-feed here.
The following is untested. One thing beforehand - you can't handle an html5 video element the same way like an embedded youtube iframe.
In case you have a video element you can interact directly with it and use the eventhandlers for play, pause and end to handle your request. A possible solution could look something like this:
$(function() {
var refreshId;
// collection of all video elements on your page
var videos = $('video');
// disable reload by clearing the interval
function blockReload() {
clearInterval(refreshId);
}
// your existing reload function
function startReload() {
refreshId = setInterval(function() {
$("#updates").load('updates.php' + '?randval=' + Math.random());
}, 30000);
}
// loop over all video elements on your page and bind
// three event handlers, one for playing, one for pausing
// and one for an ended video.
videos.each(function() {
this.addEventListener('playing', blockReload);
this.addEventListener('paused', startReload);
this.addEventListener('ended', startReload);
});
});
Since you can't control embedded elements directly, you'll need to work with the youtube API.
Instead of using the iframe from youtube, you use the API to load the video like this (example from the API page):
// This code loads the IFrame Player API code asynchronously.
// you could also use a normal script tag in that case you would load
// the lib each time.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
Next you load the video via the script library:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360'
width: '640',
videoId: 'YOURVIDEOID',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Now you can interact with the youtube video:
function onPlayerStateChange(event) {
// check if video is running...
if (event.data == YT.PlayerState.PLAYING) {
// disable interval
blockReload();
} else {
// restart interval
startReload();
}
}
I found this solution by trial and error (I used axel.michel's functions Blockreload() and StartReload()).
You can add onplay="" and onended="" to the video-tag (it also works for the audio-tag). onplay="" loads the function Blockreload(), onended="" loads the function StartReload().
It looks like this:
<video id="test" onplay="BlockReload()" onended="StartReload()" width="800" controls>
<source src="*video source*">
Jouw browser ondersteund onze videoplayer niet.
</video>

How can you stop a Slick Slider animation when a YouTube video starts playing using the Google IFrame Player API?

I have a video that is included in my Slick Slider. According to the Slick documentation you need to initialize the slider when the document is ready, however, I am not able to add the Google Youtube Iframe Player API inside of this same document.ready statement. As these two are separated my console warns me that slider cannot be found (variable set to the slick slider). Below is an example of my code. My goal is to turn off the Slick Slider animation when starting the YouTube video and turn on the animation when the YouTube video stops. As it stands on the first video play the slider animation does not end and rotates to the next slide. How can I make the slider stop animating when playing the video but start when stopping the video?
===== JavaScript =====
$(document).ready(function(){
var slider = $('.mainSlider').slick({
slidesToShow: 1,
autoplay: false,
autoplaySpeed: 5000
});
slider.slickPlay();
$('.mainSlider').on('beforeChange', function(){
line.set(0);
line.animate(1.0);
});
});
/* youtube video in slider */
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '400',
width: '100%',
videoId: 'nisAy26sItM',
events: {
'onStateChange':onPlayerStateChange
}
});
}
//when the video starts to play move the introduction content down
var done = false;
function onPlayerStateChange(event) {
if ( event.data == 1)
{
//move the introduction content down
$('#introContent').animate({top: '0px' }, 500 );
$('#services').animate({'margin-top': '0px'}, 500);
// if you play the video then you need to get rid of bxSlider autoplay
console.log('pause');
slider.slickPause();
}
if ( event.data == -1 || event.data == 2)
{
$('#introContent').animate({top:'-165px'}, 500);
$('#services').animate({'margin-top': '-100px'}, 500);
line.stop();
$('.mainSlider').slick('slickPlay');
}
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
//when the video stops move the introduction content back to were it was

Detect end of Youtube video inside the Youtube website in Javascript

I want to detect the end of a Youtube video I am watching on the Youtube website with Javascript.
I know they have an API for that, I tried to loaded it in the page with GreaseMonkey, but it doesn't seem to work. Maybe the API is only for embeded videos on other websites?
Here is what I have so far:
if (window.location.href.indexOf("&enablejsapi=1") == -1)
{
window.location = window.location.href + "&enablejsapi=1";
}
var api = document.createElement('script');
api.type = 'text/javascript';
api.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(api);
var onFinish = document.createElement('script');
onFinish.type = 'text/javascript';
var onFinishContent = "function onPlayerStateChange(event) { console.log('test'); if (event.data == YT.PlayerState.ENDED) { console.log('end'); } }"
var textNode = document.createTextNode(onFinishContent);
onFinish.appendChild(textNode);
document.body.appendChild(onFinish);
function onPlayerStateChange(event)
{
console.log("test");
if (event.data == YT.PlayerState.ENDED)
{
console.log("end");
}
}
Like you can see, I tried to make the onPlayerStateChange function callable in two ways, one directly with Greasemonkey, and the second one by injecting a script node. Both of them doesn't work, I never see the "test" message I display in the console.
Does anyone know why I can't seem to be able to load the API?
Sebastian Simon's comment-answer in the year 2015:
document.querySelector("video").addEventListener("ended",
() => alert("Video ended!")});
I checked that this still works in the year 2022.

Fire an event on play of youtube iframe embed

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;
}

how do i program the youtube embed player to unmute when clicked

How do I set the youtube embedded player to unmute upon clicking it. You can see the embedded player i'm referring to at http://www.harvestarmy.org home page. It's the one at the right where it says "Latest Videos from YouTube. I set it up to be muted by default, but I want it to automatically unmute when someone clicks it.
Here is the code I used:
<!-- 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');
// This is a protocol-relative URL as described here:
// http://paulirish.com/2010/the-protocol-relative-url/
// If you're testing a local page accessed via a file:/// URL, please set tag.src to
// "https://www.youtube.com/iframe_api" instead.
tag.src = "//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: '98',
width: '175',
playerVars: {
'list': 'UUFwY5Al1Doy7f0MdKnJ-gaw',
'modestbranding': 1,
'showinfo': 0,
'autoplay': 1
},
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
}
</script>
Thank you for that answer! I implemented it a little differently, adding it to the onYouTubeIframeAPIReady function.
I also reversed the initialized value of the isUnMuted variable. Functionally it is the same, but makes more sense this way.
var player;
var isUnMuted = false;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('youTube', {
videoId: '[myVideoId]',
playerVars: {
'rel': 0,
},
events: {
'onReady': function() {
player.mute();
player.playVideo();
},
'onStateChange': function () {
if (player.isMuted() && player.getPlayerState() == 2 && !isUnMuted) {
player.unMute();
player.playVideo();
isUnMuted = true;
}
}
}
});
}
This mimics closely the behavior of embedded videos in a Facebook newsfeed.
I don't think it is possible, because there is not such thing as a 'click' or 'activate' event. However, you may try adding an event handler to the "onStateChange" event and unmute and unpause your player. I haven't tried it, but give it a try and see if this works:
var isUnMuted = true;
player.addEventListener("onStateChange", function(event) {
if( player.isMuted() && player.getPlayerState() == 2 && isUnMuted ) {
player.unMute();
player.playVideo(); // resume playback
isUnMuted = false; // you want to run this once only!
}
});
This works. But unfortunately the pause icon fades in when the video is clicked. Even the video continues to run it is not a clean solution.
I fixed it by placing a <div> with exactly the same size above the actual video iframe and use its click() function to unmute the video.
HTML:
<div class="video-container">
<div class="video-dummy">
</div>
<div id="player">
</div>
</div>
CSS:
.video-container {
position: relative;
width: 640px;
height: 390px;
}
.video-dummy {
width: 640px;
height: 390px;
position: absolute;
}
Javascript:
$('.video-dummy').click(function(){
player.unMute();
});
This works out well for me.

Categories