YouTube API with Foundation Modal - javascript

I'm trying to show & autoplay youtube videos in a modal when a user clicks a link.
I have this working for the first video, however subsequent videos open the initial video.
During debugging, I noticed that the alert of the videoID fres as many times as the buttons have been clicked with the ID of the previous buttons. This seems like it is relevant.
<script src="//www.youtube.com/player_api"></script>
<script>
function onYouTubePlayerAPIReady() {
$('.feature-modal-btn').on('click', function(e){
e.preventDefault();
var btn = $(this);
//var modal = "#YTMODAL";
var ytVideoID = btn.data('ytvideoid');
$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
alert(ytVideoID);
player = new YT.Player('feature-video', { //Add the player
width: '800',
videoId: ytVideoID,
playerVars: {
rel : 0,
theme : 'light',
showinfo : 0,
showsearch : 0,
autoplay : 1,
autohide : 1,
modestbranding : 1
},
events: {
}
});
});
$(document).on('close.fndtn.reveal', '[data-reveal]', function () {
$('#YTMODAL .flex-video #feature-video').remove();
$('#YTMODAL .flex-video #feature-video iframe').remove();
player = '';
$('#YTMODAL .flex-video').append('<div id="feature-video" />');
});
});
}
</script>
<a href="" class="feature-modal-btn" data-ytvideoid="o_nA1nIT2Ow" data-reveal-id="YTMODAL">
<a href="" class="feature-modal-btn" data-ytvideoid="p-iFl4qhBsE" data-reveal-id="YTMODAL">
<div id="YTMODAL" class="reveal-modal full" data-reveal >
<div class="video-container flex-video widescreen">
<div id="feature-video">[this div will be converted to an iframe]</div>
</div>
<a class="close-reveal-modal">×</a>
</div>
I am using foundations modal reveal.
http://foundation.zurb.com/docs/components/reveal.html
How can i adjust my code so the correct movie is shown each time a link is clicked?
UPDATE
I created a codepen to show what's happening. try opening & closing the modals using the one & two links
http://codepen.io/anon/pen/HkoKg

This was just me getting my code muddled, not something specific to YT or Reveal working version in this pen
http://codepen.io/anon/pen/HkoKg?editors=101
$(document).foundation();
var ytvideoid;
$('.feature-modal-btn').on('click', function(e){
ytvideoid = $(this).data('ytvideoid')
});
$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
var modal = $(this);
//console.log(modal);
player = new YT.Player('feature-video', { //Add the player
width: '800',
videoId: ytvideoid,
playerVars: {
rel : 0,
theme : 'light',
showinfo : 0,
showsearch : 0,
autoplay : 1,
autohide : 1,
modestbranding : 1
},
events: {
}
});
});
$(document).on('close.fndtn.reveal', '[data-reveal]', function () {
$('#YTMODAL .flex-video #feature-video').remove();
$('#YTMODAL .flex-video').append('<div id="feature-video" />');
});

Related

Owl carousel autoplay only plays once when using the autoplay trigger on mouseenter

I am trying to only start autoplay when a user sees the carousel (else newest posts won't be visible by the time the user scrolls to the carousel element) using this code:
var App = (function(window){
"use strict";
var _this = null;
var cacheCollection = {};
return{
init : function(){
_this = this;
this.autoplayonsection();
},
autoplayonsection: function(){
var fbowl = $('#r-latest-news-slider');
$('#r-latest-news').on('mouseenter', function() {
console.log('autoplay');
fbowl.trigger('play.owl.autoplay', [1000]);
});
$('#r-latest-news').on('mouseleave', function() {
console.log('stop autoplay');
fbowl.trigger('stop.owl.autoplay');
});
},
LatestNewsCarousel: function(){
if($("#r-latest-news-slider").length > 0){
var owl = $('#r-latest-news-slider').owlCarousel({
loop:true,
margin: 30,
items: 4,
nav: false,
dots: true,
autoplay:false,
autoplayTimeout:1000,
responsive:{
0:{
items:2
},
600:{
items:2
},
1000:{
items:4
}
}
})
}
},
}
})(window);
$(document).ready(function($) {
$('#preloader').fadeOut('slow',function(){$(this).remove();});
App.init();
});
The console log works fine and I see the texts when I move my mouse over the element or leave it. But for some reason the autoplay only works once, it slides once and then stops until I leave with my mouse en re enter the element at which time it plays once again.
This is the element that contains my carousel:
<div class="owl-carousel r-latest-news-list" id="r-latest-news-slider">
Why does it only play once? What can I do to fix it?
I found out that the minimum value for autoplayTimeout is 1233...below than 1233 will not working...
below is the example of working options:
{
items:1,
loop:true,
smartSpeed:1200,
autoplay:true,
autoplayTimeout:1500, //if you set this value to 1000, it will NOT working
autoplayHoverPause:true,
}

Change YouTube video size with jQuery

I am trying to make a YouTube video width change when the "onStateChange" event fires on 1(playing) and then make it come back to its original size on 0(ended) and 2(paused).
I am very new to JavaScript and jQuery. But let's say I have this
<section><iframe id="player" src="https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1"></iframe></section>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player( 'player', {
events: { 'onStateChange': onPlayerStateChange }
});
}
</script>
<script src="https://www.youtube.com/iframe_api"></script>
why does this jquery does not work?
jQuery(document).ready(function($) {
YT.PlayerState.ENDED = function(e) {
$('section iframe').animate({ width: "50%"}, 'slow')};
YT.PlayerState.PAUSED = function(e) {
$('section iframe').animate({ width: "50%"}, 'slow')};
YT.PlayerState.PLAYING = function(e) {
$('section iframe').animate({ width: "100%" }, 'slow');
}
the API information I have got comes from here https://developers.google.com/youtube/iframe_api_reference#Events

ShowHide plugin: Fade in instead of toggle?

I'm using the ShowHide Plugin and I'm trying to get it to fade in instead of toggle/slide into view. Here is what I have:
showHide.js
(function ($) {
$.fn.showHide = function (options) {
//default vars for the plugin
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide'
};
var options = $.extend(defaults, options);
$(this).click(function () {
// optionally add the class .toggleDiv to each div you want to automatically close
$('.toggleDiv').slideUp(options.speed, options.easing);
// this var stores which button you've clicked
var toggleClick = $(this);
// this reads the rel attribute of the button to determine which div id to toggle
var toggleDiv = $(this).attr('rel');
// here we toggle show/hide the correct div at the right speed and using which easing effect
$(toggleDiv).slideToggle(options.speed, options.easing, function() {
// this only fires once the animation is completed
if(options.changeText==1){
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
}
});
return false;
});
};
})(jQuery);
$(document).ready(function(){
$('.show_hide').showHide({
speed: 1000, // speed you want the toggle to happen
easing: '', // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
changeText: 1, // if you dont want the button text to change, set this to 0
showText: 'View',// the button text to show when a div is closed
hideText: 'Close' // the button text to show when a div is open
});
});
HTML
<a class="show_hide" href="#" rel="#slidingDiv">View</a></pre>
<div id="slidingDiv" class="toggleDiv" style="display: none;">Fill this space with really interesting content.</div>
<pre>
<a class="show_hide" href="#" rel="#slidingDiv_2">View</a></pre>
<div id="slidingDiv_2" class="toggleDiv" style="display: none;">Fill this space with really interesting content.</div>
<pre>
There is a bug in the line $('.toggleDiv').slideUp(options.speed, options.easing);, here you should not slideup the target div - use $('.toggleDiv').not(toggleDiv).slideUp(options.speed, options.easing);
Try
(function ($) {
$.fn.showHide = function (options) {
//default vars for the plugin
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide'
};
var options = $.extend(defaults, options);
$(this).click(function () {
// this var stores which button you've clicked
var toggleClick = $(this);
// this reads the rel attribute of the button to determine which div id to toggle
var toggleDiv = $(this).attr('rel');
// optionally add the class .toggleDiv to each div you want to automatically close
$('.toggleDiv').not(toggleDiv).slideUp(options.speed, options.easing);
// here we toggle show/hide the correct div at the right speed and using which easing effect
$(toggleDiv).slideToggle(options.speed, options.easing, function () {
// this only fires once the animation is completed
if (options.changeText) {
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
}
});
return false;
});
};
})(jQuery);
Demo: Fiddle

Fancybox - Embedded YouTube (using YouTube API) doesn't load on iOS

I am using Fancybox to display videos that are uploaded to YouTube. I want to carry out actions when the video has ended (in this case, moving from the video to the next element in the group - an image), so I am also using the YouTube API.
The page works perfectly fine on desktop browsers (and I think Android but I haven't tested that extensively yet), but on my iPhone it fails to load the video. The overlay is coming up, but it appears to try to autoplay the video and then becomes black.
I am currently using jQuery 1.8.3 (I tried it with 1.10 but it didn't work, so I gave downgrading a shot) and Fancybox 2.1.5.
Here's the relevant HTML:
<div class="content" id="main">
<div id="logo">
<a class="fancybox fancybox.iframe" id="logo-link" data-fancybox-group="group01"href="http://www.youtube.com/embed/Bc0qNwaSxlM"></a>
<a class="fancybox" id="v-link" data-fancybox-group="group01" data-fancybox-type="image" href="img/superhard_v.png" title="
</div>
</div>
JavaScript:
window.onYouTubePlayerAPIReady = function() {
// Initialise the fancyBox after the DOM is loaded
$(document).ready(function() {
$(".fancybox")
.attr('rel', 'gallery')
.fancybox({
helpers: {
media: {},
overlay : {
css : {
'background' : 'rgba(0, 0, 0, 0.95)'
}
}
},
youtube : {
vq: 'hd1080'
},
padding: 0,
margin: 30,
autoSize: false,
arrows: false,
'closeBtn' : false,
beforeShow : function() {
// Find the iframe ID
var id = $.fancybox.inner.find('iframe').attr('id');
// Create video player object and add event listeners
var player = new YT.Player(id, {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
if (this.index === 1) {
$('.fancybox-outer').css("padding-bottom","100px");
}
},
afterShow: function() {
if (this.index === 1) {
$("img.fancybox-image").click(function(event) {
event.preventDefault();
newLocation = "vanity/";
$('body').fadeOut(1000, newPage);
});
$('#return-link').click(function(event) {
event.preventDefault();
$.fancybox.close();
});
}
},
tpl: {
wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin" style="background-color:transparent;"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>'
},
iframe: {
preload: false
}
});
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
// Fires when the player's state changes.
function onPlayerStateChange(event) {
// Go to the image after the current one is finished playing
if (event.data === 0) {
setTimeout(function(){$.fancybox.next()},1250);
}
}
I put in autoSize and preload: false for iframe because of solutions I came across from other peoples questions, but they did not work. I was particularly hopeful the latter would work because of this question and the example JSFiddle, but it didn't work, which led me to believe that maybe it's an issue with the API? I also looked at the example on the Fancybox homepage which uses the API, and it also did not work on my iPhone, further confirming my suspicion.
If anyone has a workaround or any idea of how to fix this, it would be much appreciated. Thanks!
Why not re-check the various examples used in the fancybox website:
You can try this:
*Html*
<li>
<a class="various fancybox.iframe" href="http://www.youtube.com/embed/L9szn1QQfas?autoplay=1">Youtube (iframe)</a>
</li>
Javascript:
$(document).ready(function() {
$(".various").fancybox({
maxWidth : 800,
maxHeight : 600,
fitToView : false,
width : '70%',
height : '70%',
autoSize : false,
closeClick : false,
openEffect : 'none',
closeEffect : 'none'
});
});
Our check their official fiddle for youtube iframe: This is their fiddle
Html:
<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>
<a class="fancybox fancybox.iframe" href="http://www.youtube.com/embed/L9szn1QQfas?enablejsapi=1&wmode=opaque">Video #1</a>
<br />
<a class="fancybox fancybox.iframe" href="http://www.youtube.com/embed/cYplvwBvGA4?enablejsapi=1&wmode=opaque">Video #2</a>
You can check out the remainin'

I can't get 2 javascripts to work simultaneously

On a website im building on a Joomla CMS i call inside the head tag these javascripts :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.history.js"></script>
<script type="text/javascript" src="js/jquery.galleriffic.js"></script>
<script type="text/javascript" src="js/jquery.opacityrollover.js"></script>
<script type="text/javascript">document.write('<style>.noscript { display: none; }</style>');</script>
I have two javascripts inserted on my index.php
One for a slideshow (gallerific) and another one for a dropdown menu.
The slideshow javascript :
<script type="text/javascript">
jQuery(document).ready(function($) {
// We only want these styles applied when javascript is enabled
$('div.content').css('display', 'block');
// Initially set opacity on thumbs and add
// additional styling for hover effect on thumbs
var onMouseOutOpacity = 0.9;
$('#thumbs ul.thumbs li, div.navigation a.pageLink').opacityrollover({
mouseOutOpacity: onMouseOutOpacity,
mouseOverOpacity: 1.0,
fadeSpeed: 'fast',
exemptionSelector: '.selected'
});
// Initialize Advanced Galleriffic Gallery
var gallery = $('#thumbs').galleriffic({
delay: 2500,
numThumbs: 10,
preloadAhead: 10,
enableTopPager: false,
enableBottomPager: false,
imageContainerSel: '#slideshow',
controlsContainerSel: '#controls',
captionContainerSel: '#caption',
loadingContainerSel: '#loading',
renderSSControls: true,
renderNavControls: true,
playLinkText: 'Play Slideshow',
pauseLinkText: 'Pause Slideshow',
prevLinkText: '‹ Previous Photo',
nextLinkText: 'Next Photo ›',
nextPageLinkText: 'Next ›',
prevPageLinkText: '‹ Prev',
enableHistory: true,
autoStart: true,
syncTransitions: true,
defaultTransitionDuration: 900,
onSlideChange: function(prevIndex, nextIndex) {
// 'this' refers to the gallery, which is an extension of $('#thumbs')
this.find('ul.thumbs').children()
.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
.eq(nextIndex).fadeTo('fast', 1.0);
// Update the photo index display
this.$captionContainer.find('div.photo-index')
.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
},
onPageTransitionOut: function(callback) {
this.fadeTo('fast', 0.0, callback);
},
onPageTransitionIn: function() {
var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
var nextPageLink = this.find('a.next').css('visibility', 'hidden');
// Show appropriate next / prev page links
if (this.displayedPage > 0)
prevPageLink.css('visibility', 'visible');
var lastPage = this.getNumPages() - 1;
if (this.displayedPage < lastPage)
nextPageLink.css('visibility', 'visible');
this.fadeTo('fast', 1.0);
}
});
/**************** Event handlers for custom next / prev page links **********************/
gallery.find('a.prev').click(function(e) {
gallery.previousPage();
e.preventDefault();
});
gallery.find('a.next').click(function(e) {
gallery.nextPage();
e.preventDefault();
});
/****************************************************************************************/
/**** Functions to support integration of galleriffic with the jquery.history plugin ****/
// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
// alert("pageload: " + hash);
// hash doesn't contain the first # character.
if(hash) {
$.galleriffic.gotoImage(hash);
} else {
gallery.gotoIndex(0);
}
}
// Initialize history plugin.
// The callback is called at once by present location.hash.
$.historyInit(pageload, "advanced.html");
// set onlick event for buttons using the jQuery 1.3 live method
$("a[rel='history']").live('click', function(e) {
if (e.button != 0) return true;
var hash = this.href;
hash = hash.replace(/^.*#/, '');
// moves to a new page.
// pageload is called at once.
// hash don't contain "#", "?"
$.historyLoad(hash);
return false;
});
/****************************************************************************************/
});
</script>
And the dropdown menu:
<script language="javascript" type="text/javascript">
var axm = {
openMenu: function() {
$('#newmenuheader').stop().animate({ 'height':'140px'}, "fast");
},
closeMenu: function() {
$('#newmenuheader').stop().css({'overflow': 'hidden'}).animate({'height':'55px'}, "fast");
},
};
</script>
I can get only one script run at a time not both. If one runs the other doesn't. I need to have them both.
At the time the javascript for the slideshow is running. Is there a conflict of some sort ?
Thanks in advance.
The second chunk of javascript code with the var axm needs to be added to the
jQuery(document).ready(function($) {}
Otherwise the browser doesn't know to run it. And you should re-write this function, don't use
jQuery(document).ready(function($) {}
just use
$(function(){
//your javascript and jQuery here for binding events, styles, and functions
}
this is a function that will run once the page is ready.

Categories