Youtube Video Autoplay in popup - javascript

I've made a popup and placed a youtube video in it. I set video to autoplay. But the problem is video plays when i open the page. It is auto play in global and i want it to autoplay when popup shows. I did not find any solution for it.
Currently, It playing like i have background ghost saying something.
Can anyone help?
Video Html
<iframe width="800" height="315" src="http://www.youtube.com/embed/?wmode=opaque&autoplay=1&rel=0&color=white" frameborder="0"></iframe><img alt="" class="watermark" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHcbyVSjHQlwCy3tYqOyLwSWDO4tblhxTVVjKV5R0PtFsPy9TwfA" /></div>
</div>
Calling popup
<img src="kaow.png"/>
</div>
Popup Content
<div id="video_pop" class="reveal-modal medium">
<a class="close-reveal-modal"></a>
<div>
<iframe width="800" height="315" src="http://www.youtube.com/embed/?wmode=opaque&autoplay=1&rel=0&color=white" frameborder="0"></iframe><img alt="" class="watermark" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQHcbyVSjHQlwCy3tYqOyLwSWDO4tblhxTVVjKV5R0PtFsPy9TwfA" /></div>
</div>
JS
Foundation.libs.reveal = {
name: "reveal",
version: "4.2.2",
locked: !1,
settings: {
animation: "fadeAndPop",
animationSpeed: 250,
closeOnBackgroundClick: !0,
closeOnEsc: !0,
dismissModalClass: "close-reveal-modal",
bgClass: "reveal-modal-bg",
open: function() {},
opened: function() {},
close: function() {},
closed: function() {},
bg: a(".reveal-modal-bg"),
css: {
open: {
opacity: 0,
visibility: "visible",
display: "block"
},
close: {
opacity: 1,
visibility: "hidden",
display: "none"
}
}
},
init: function(b, c, d) {
return Foundation.inherit(this, "data_options delay"), "object" == typeof c ? a.extend(!0, this.settings, c) : "undefined" != typeof d && a.extend(!0, this.settings, d),
"string" != typeof c ? (this.events(), this.settings.init) : this[c].call(this, d);
},
events: function() {
var b = this;
return a(this.scope).off(".fndtn.reveal").on("click.fndtn.reveal", "[data-reveal-id]", function(c) {
c.preventDefault();
if (!b.locked) {
var d = a(this), e = d.data("reveal-ajax");
b.locked = !0;
if ("undefined" == typeof e) b.open.call(b, d); else {
var f = e === !0 ? d.attr("href") : e;
b.open.call(b, d, {
url: f
});
}
}
}).on("click.fndtn.reveal", this.close_targets(), function(c) {
c.preventDefault();
if (!b.locked) {
var d = a.extend({}, b.settings, b.data_options(a(".reveal-modal.open")));
if (a(c.target)[0] === a("." + d.bgClass)[0] && !d.closeOnBackgroundClick) return;
b.locked = !0, b.close.call(b, a(this).closest(".reveal-modal"));
}
}).on("open.fndtn.reveal", ".reveal-modal", this.settings.open).on("opened.fndtn.reveal", ".reveal-modal", this.settings.opened).on("opened.fndtn.reveal", ".reveal-modal", this.open_video).on("close.fndtn.reveal", ".reveal-modal", this.settings.close).on("closed.fndtn.reveal", ".reveal-modal", this.settings.closed).on("closed.fndtn.reveal", ".reveal-modal", this.close_video),
a("body").bind("keyup.reveal", function(c) {
var d = a(".reveal-modal.open"), e = a.extend({}, b.settings, b.data_options(d));
27 === c.which && e.closeOnEsc && d.foundation("reveal", "close");
}), !0;
},
open: function(b, c) {
if (b) if ("undefined" != typeof b.selector) var d = a("#" + b.data("reveal-id")); else {
var d = a(this.scope);
c = b;
} else var d = a(this.scope);
if (!d.hasClass("open")) {
var e = a(".reveal-modal.open");
"undefined" == typeof d.data("css-top") && d.data("css-top", parseInt(d.css("top"), 10)).data("offset", this.cache_offset(d)),
d.trigger("open"), e.length < 1 && this.toggle_bg(d);
if ("undefined" == typeof c || !c.url) this.hide(e, this.settings.css.close), this.show(d, this.settings.css.open); else {
var f = this, g = "undefined" != typeof c.success ? c.success : null;
a.extend(c, {
success: function(b, c, h) {
a.isFunction(g) && g(b, c, h), d.html(b), a(d).foundation("section", "reflow"),
f.hide(e, f.settings.css.close), f.show(d, f.settings.css.open);
}
}), a.ajax(c);
}
}
},
close: function(b) {
var b = b && b.length ? b : a(this.scope), c = a(".reveal-modal.open");
c.length > 0 && (this.locked = !0, b.trigger("close"), this.toggle_bg(b), this.hide(c, this.settings.css.close));
},
close_targets: function() {
var a = "." + this.settings.dismissModalClass;
return this.settings.closeOnBackgroundClick ? a + ", ." + this.settings.bgClass : a;
},
toggle_bg: function(b) {
0 === a(".reveal-modal-bg").length && (this.settings.bg = a("<div />", {
"class": this.settings.bgClass
}).appendTo("body")), this.settings.bg.filter(":visible").length > 0 ? this.hide(this.settings.bg) : this.show(this.settings.bg);
},
EDITED:
I am using Foundation 5 Reveal Model for popup: http://foundation.zurb.com/docs/components/reveal.html

I think you want something like that :
LIVE EXAMPLE
Basically i use the API Javascript to add actions play and pause to the video.
And i use default function of Foundation to add an event when to the player.
HTML
Click Me For A Modal
<div id="myModal" class="reveal-modal" data-reveal>
<h2>Awesome</h2>
<div id="player"></div>
<a class="close-reveal-modal">×</a>
</div>
JS
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: '315',
width: '560',
videoId: 'l-gQLqv9f4o',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
//player is playing
} else {
//player is paused
}
}
function stopVideo() {
player.stopVideo();
}
function playVideo() {
player.playVideo();
}
function pauseVideo() {
player.pauseVideo();
}
$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
playVideo();
});
$(document).on('closed.fndtn.reveal', '[data-reveal]', function () {
pauseVideo();
});

From the YouTube JavaScript Player API Reference:
The JavaScript API allows users to control the YouTube chromeless or
embedded video players via JavaScript. Calls can be made to play,
pause, seek to a certain time in a video, set the volume, mute the
player, and other useful functions.
You can use the API's player.playVideo(), player.pauseVideo() and player.stopVideo() method.

So, Ive read a bunch of different threads on this and most of what Ive seen is pretty complicated. I went a much more simple route.
$('.reveal-overlay').click(function(e){
var loc = document.getElementById('myFrame').src;
var stoploc = loc.replace("?autoplay=1", "");
document.getElementById('myFrame').setAttribute('src', stoploc);
});
$('.playVideo').click(function(e){
var loc = document.getElementById('myFrame').src;
var autoloc = loc + "?autoplay=1";
document.getElementById('myFrame').setAttribute('src', autoloc);
});
This will basically just append ?autoplay=1 to a YouTube video once the modal is opened. The class .playVideo is on whatever button youre using to open your modal window.
The class .reveal-overlay is created by Foundation. So when the overlay is clicked it removes any ?autoplay=1 from the video url.
Hope this helps anyone running into this problem. It's simple and should work for multiple different videos, plus, if someone has js turned off, it won't play anything in the background.
One more thing, the video you load should be a regular non-autoplay video. This will turn it into an autoplay after clicked ony and return it to non-autoplay when closed.

Thanks to #Jarod Means script! It works and I uses it since it only requires jQuery (Simple solution = Great solution). But I developed it for multiple video clips, which is great in slideshows, as an example or whenever you need this solution for more then one clip in the same dom. I also made it so it is completely in jQuery.
Just posting it so you can use it as you wish.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>Youtube-player test</title>
<style>
.youtube-player iframe {
display: none;
}
.youtube-player.active iframe {
display: block;
}
</style>
</head>
<body>
<div class="youtube-player">
<iframe width="560" height="315" src="https://www.youtube.com/embed/XzXjuDM_Z54" frameborder="0" allowfullscreen></iframe>
Open window
Close window
</div>
<div class="youtube-player">
<iframe width="560" height="315" src="https://www.youtube.com/embed/l2EYyzXJIdE" frameborder="0" allowfullscreen></iframe>
Open window
Close window
</div>
<script>
jQuery('.youtube-player').each(function(){
jQuery(this).on('click', '.youtube-link-start', function(){
jQuery(this).parent().addClass('active');
var loc = $(this).siblings('iframe').attr('src');
var startloc = loc + "?autoplay=1";
$(this).siblings('iframe').attr('src', startloc);
});
jQuery(this).on('click', '.youtube-link-stop', function(){
jQuery(this).parent().removeClass('active');
var loc = $(this).siblings('iframe').attr('src');
var stoploc = loc.replace("?autoplay=1", "");
$(this).siblings('iframe').attr('src', stoploc);
});
});
</script>
</body>
</html>
I guess you can keep on changing/developing this with html, css and jQuery to whatever fit your needs. :)

Related

How to know if a video from <iframe> is playing (youtube AND vimeo)

I have an iframe of youtube / vimeo content and I would know if the video is playing when my function is executed.
Actually, when someone click on an image, my code set the right video corresponding at this image in the iframe. and i have a button which pause and hide my iframe
I found this with youtube API: getPlayerState() ,
and getPaused() from vimeo API.
I don't want to use click event, I would like to be able to know the pauseState at everytime !
https://developers.google.com/youtube/iframe_api_reference?hl=fr
https://developer.vimeo.com/player/sdk/reference#events-for-text-tracks
<iframe id="player" class="center" width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<script src="https://player.vimeo.com/api/player.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
function loadVideo(id) {
var videoPlayer = document.getElementById('videoPlayer');
var player = document.getElementById('player');
var url = player.src;
switch (id) {
case 1:
url = "https://www.youtube.com/embed/n1tswFfg-Ig?enablejsapi=1";
break ;
case 2:
url = "https://player.vimeo.com/video/237596019?api=1";
break ;
default:
callPlayer("pauseVideo");
break ;
function callPlayer(func, args) {
var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; ++i) {
if (iframes[i]) {
var src = iframes[i].getAttribute('src');
if (src) {
if (src.indexOf('youtube.com/embed') != -1) {
var player = new YT.Player(iframes[i], {});
//2 lines below doesn't work
var value = player.getPlayerState();
alert('value');
iframes[i].contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
}), "*");
}
if (src.indexOf('player.vimeo.com/video') != -1) {
var player = new Vimeo.Player(iframes[i]);
switch (func) {
case 'pauseVideo':
//always show 'false', never 'true'
if (player.getPaused() == true ) {
alert('true');
}else {
alert('false');
}
player.pause();
break ;
default:
break ;
}
}
}
}
}
}
i use alert to know if something is working, and with this code, the youtube alert does not work , and the vimeo alert always show 'false'.
Thanks for your help
Maybe the issue can be related to the use of the same iframe, which ends up messing up the functions of each type of video. In this way, a solution would be to use more than one iframe that would be displayed or hidden as needed.
Another problem that has been reported is that starting the YouTube video directly through <iframe> does not end up activating the listening functions. So, the ideal is to follow as recommended in the YouTube Player API documentation and start the video with a <div>, so that .getPlayerState() and other methods work well.
// Buttons to switch videos
function changeVideo (btn) {
if (btn.classList.contains("active")) {
return;
}
document.querySelector('.buttons .active').classList.remove('active');
document.querySelector('.video .active').classList.remove('active');
document.querySelector("." + btn.dataset.video + "-video").classList.add('active');
btn.classList.add('active');
}
// YouTube starter
let youtubePlayer;
function onYouTubeIframeAPIReady() {
youtubeVideo = new YT.Player('youtubePlayer', {
height: '315',
width: '560',
videoId: 'tgbNymZ7vqY'
});
}
// YouTube - check if it's paused
function checkYoutubePaused() {
let state = youtubeVideo.getPlayerState();
if (state <= 0 || state == 2 || state == 5) {
return true;
}
return false;
}
// Vimeo starter
const vimeoIframe = document.querySelector('.vimeo-video');
const vimeoPlayer = new Vimeo.Player(vimeoIframe);
// Vimeo - check if it's paused
async function checkVimeoPaused() {
let state;
await vimeoPlayer.getPaused().then(function(paused) {
state = paused;
});
return state;
}
// My Function
async function myFunction() {
vimeoState = await checkVimeoPaused();
let youtubePaused = checkYoutubePaused() ? "PAUSED" : "RUNNING";
let vimeoPaused = vimeoState ? "PAUSED" : "RUNNING";
alert("Youtube Video is " + youtubePaused + "\n" + "Vimeo Video is " + vimeoPaused);
}
.youtube-video {
display: none;
}
.vimeo-video {
display: none;
}
.video .active {
display: inline;
}
.buttons .active {
color: #ffffff;
background-color: #333333;
}
<script src="https://player.vimeo.com/api/player.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<div class="video">
<div id="youtubePlayer" class="youtube-video active"></div>
<iframe class="vimeo-video" src="https://player.vimeo.com/video/120680495" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div>
<span class="buttons">
<button data-video="youtube" class="active" onclick="changeVideo(this)">Youtube Video</button>
<button data-video="vimeo" onclick="changeVideo(this)">Vimeo Video</button>
</span>
<span>
<button onclick="myFunction()">Run My Function</button>
</span>
</div>

How to dynamically change YouTube player's options

I have a chatroom and I'm making it better for practice purposes; there's already socket.io running on a node.js server, but I decided to make my own radio.
Here is the code belonging to the radio:
HTML:
<div data-video="1cDxhcAOpa8"
data-autoplay="1"
data-loop="1"
id="youtube-audio">
<form id="formMusica">
<select id="selectGenero">
<option value="edm" selected>EDM</option>
<option value="rock">Rock</option>
</select>
</form>
<script src="https://www.youtube.com/iframe_api"></script>
<script id="scriptYt" src="/yt.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $container = $('#youtube-audio');
var $formGenero = $('#formMusica');
var $select = $('#selectGenero');
var $genero;
$formGenero.submit(function (e) {
e.preventDefault();
});
$select.change(function () {
$genero = $select.val();
buildPlayer();
});
var radios = [{
'name': 'Pixl',
'genre': 'EDM',
'type': 'video',
'ytd_id': 'cDxhcAOpa8'
}, {
'name': 'Best Rock Music',
'genre': 'Rock',
'type': 'playlist',
'ytd_id': 'PLZN_exA7d4RVmCQrG5VlWIjMOkMFZVVOc'
}];
function buildPlayer() {
var genreData = getGenreData();
// Erase all to build again
$container.html('');
if (genreData.type === 'video') {
$container.attr('data-video', genreData.ytd_id)
.removeAttr('data-listtype').removeAttr('data-list');
}
else if (genreData.type === 'playlist') {
$container.attr('data-list', genreData.ytd_id)
.attr('data-listtype', genreData.type).removeAttr('data-video');
}
// #scriptYt's code will be below
$('#scriptYt').remove();
$('body').append('<script id="scriptYt" src="/yt.js"><\/script>');
onYouTubeIframeAPIReady();
}
function getGenreData() {
for (i = 0; i < radios.length; i++) {
if (radios[i].genre.toLowerCase() === $genero) {
return radios[i];
}
}
}
});
</script>
YT.JS:
var r;
function onYouTubeIframeAPIReady() {
var $container = $('#youtube-audio');
$container.append('<i class="fa fa-2x" id="youtube-icon"></i>');
var $icon = $('#youtube-icon');
$icon.css({ 'transition': '0.5s', 'cursor': 'pointer' });
$container.append('<div id="youtube-player"></div>');
var o = function (e) {
var a = e ? 'fa-stop' : 'fa-play';
if (a === 'fa-stop') {
$icon.addClass('fa-stop');
$icon.addClass('text-danger');
$icon.removeClass('fa-play');
$icon.removeClass('text-success');
}
else if (a === 'fa-play') {
$icon.addClass('fa-play');
$icon.addClass('text-success');
$icon.removeClass('fa-stop');
$icon.removeClass('text-danger');
}
};
$container.click(function () {
r.getPlayerState() === YT.PlayerState.PLAYING || r.getPlayerState() === YT.PlayerState.BUFFERING ? (r.pauseVideo(), o(!1)) : (r.playVideo(), o(!0));
});
r = new YT.Player('youtube-player', {
height: '0',
width: '0',
videoId: $container.data('video'),
playerVars: {
listType: $container.data('listtype'),
list:$container.data('list'),
autoplay: $container.data('autoplay'),
loop: $container.data('loop')
},
events: {
onReady: function (e) {
r.setPlaybackQuality('small'),
o(r.getPlayerState !== YT.PlayerState.CUED)
},
onStateChange: function (e) {
e.data === YT.PlayerState.ENDED && o(!1)
}
}
});
}
It works perfectly when you first load the page, then when you select other genre it stays the same video, I tried removing everything inside #youtube-audio and the script tag, then inserting the tag again and calling the method, it loads the same video every time.
OBS: I know JavaScript well, but I prefer jQuery if possible.
UPDATE: Thanks to #matthewninja, r.loadVideoById() works, but still I need to work with playlists, r.loadPlaylist() doesn't work.
There's no need to destroy the previously existing player element in order to change the video. According to the YouTube Player API Reference page, you can simply call player.loadVideoById(videoId) to change the song.
With that being said, here's a solution that I've implemented using a button that changes the song:
HTML
<html>
<head>
<script
src="http://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
</head>
<body>
<div data-video="1cDxhcAOpa8"
data-autoplay="1"
data-loop="1"
id="youtube-audio">
<button onclick="changeSong()">change song</button>
<script src="https://www.youtube.com/iframe_api"></script>
<script id="scriptYt" src="yt.js"></script>
</div>
</body>
</html>
yt.js
var r;
function onYouTubeIframeAPIReady() {
var $container = $('#youtube-audio');
$container.append('<i class="fa fa-2x" id="youtube-icon"></i>');
var $icon = $('#youtube-icon');
$icon.css({ 'transition': '0.5s', 'cursor': 'pointer' });
$container.append('<div id="youtube-player"></div>');
var o = function (e) {
var a = e ? 'fa-stop' : 'fa-play';
if (a === 'fa-stop') {
$icon.addClass('fa-stop');
$icon.addClass('text-danger');
$icon.removeClass('fa-play');
$icon.removeClass('text-success');
}
else if (a === 'fa-play') {
$icon.addClass('fa-play');
$icon.addClass('text-success');
$icon.removeClass('fa-stop');
$icon.removeClass('text-danger');
}
};
$container.click(function () {
r.getPlayerState() === YT.PlayerState.PLAYING || r.getPlayerState() === YT.PlayerState.BUFFERING ? (r.pauseVideo(), o(!1)) : (r.playVideo(), o(!0));
});
r = new YT.Player('youtube-player', {
height: '0',
width: '0',
videoId: $container.data('video'),
playerVars: {
listType: $container.data('listtype'),
list:$container.data('list'),
autoplay: $container.data('autoplay'),
loop: $container.data('loop')
},
events: {
onReady: function (e) {
r.setPlaybackQuality('small'),
o(r.getPlayerState !== YT.PlayerState.CUED)
},
onStateChange: function (e) {
e.data === YT.PlayerState.ENDED && o(!1)
}
}
});
}
function changeSong(){
r.loadVideoById("mHpZ-ZFZwiY");
}
When the user clicks the button, the video will change to a video specified by the argument given to loadVideoById. Given this functionality, you should have a much easier time implementing your ideal solution. You could modify your changeSong() function to accept an argument from a <select> element.

Cannot read property 'apply' of undefined - Youtube Api

I created the following code to make videos play on hover:
var player = [];
var el_number;
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady(i, el_number)
}
});
}
}
function onPlayerReady(number, elnumber) {
$(".article:eq("+elnumber+")").on({
'mouseover': function() {
player[number].playVideo();
},
'mouseout': function() {
player[number].pauseVideo();
}
});
}
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/(video_id)?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
It works perfectly fine, but after some time of loading scripts it shows me this error in the console:
Uncaught TypeError: Cannot read property 'apply' of undefined www-widgetapi.js:65
at K.g.I (www-widgetapi.js:65)
at W.g.l (www-widgetapi.js:114)
at W.g.J (www-widgetapi.js:127)
at S.g (www-widgetapi.js:143)
at k (www-widgetapi.js:95)
I ckecked Opera and Edge there is no error. After disabling every extention there is still that problem in Chrome. What is the root of the problem here?
I think it's an issue with your callback definition :
onPlayerReady(i, el_number)
onPlayerReady takes the event data as parameter. To get the player, you can call event.target and store some data inside this object
For instance :
var player = [];
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady
}
});
player[i].el_number = el_number;
}
}
function onPlayerReady(event) {
console.log("event.target.el_number : " + event.target.el_number);
$(".article:eq(" + event.target.el_number + ")").on({
'mouseover': function() {
event.target.playVideo();
},
'mouseout': function() {
event.target.pauseVideo();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/B_hLfhccYf0?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
You can find a jsfiddle here

data-src tags working in index.html, but not working in angular views

I am relatively new to angular and to javascript, so please accept my apologies if I sound stupid.
I am trying to incorporate a theme to angular. I have noticed that if I include the whole code to index.html, the website works, but when I shift the code to controllers and call them via <div ui-view></div>, the rendered page misses some key components.
For e.g. the following causes a header background video to be played:
<img src="img/video_fix.png" alt="" class="header-video--media" data-video-src="video/intro" data-teaser-source="video/intro" data-provider="Vimeo" data-video-width="1920" data-video-height="960">
If I include it in index.html, it works fine. But if I include it in a controller, it does not render.
Another code that does not render:
<section class="parallax-window" data-parallax="scroll" data-image-src="img/bg_office.jpg" data-natural-width="1200" data-natural-height="600">
Upon searching, I came to know that you cannot include jQuery plugins directly in views, but must do so in directives. However, I have not been able to find any guide that may enable me to understand how to incorporate jQuery plugins in angular views.
The following code is included in index.html:
<script src="js/video_header.js"></script>
<script>
$(document).ready(function () {
'use strict';
HeaderVideo.init({
container: $('.header-video'),
header: $('.header-video--media'),
videoTrigger: $("#video-trigger"),
autoPlayVideo: true
});
});
</script>
Here is the code for video_header.js
var HeaderVideo = function (e, i) {
var o = {
container: e(".header-video"),
header: e(".header-video--media"),
videoTrigger: e("#video-trigger"),
videoCloseTrigger: e("#video-close-trigger"),
teaserVideo: e("#teaser-video"),
autoPlayVideo: !1
}, r = function (i) {
o = e.extend(o, i), t(), d(), a(), o.videoCloseTrigger.hide(), videoDetails.teaser && n(), o.autoPlayVideo && l()
}, t = function () {
return videoDetails = {
id: o.header.attr("data-video-src"),
teaser: o.header.attr("data-teaser-source"),
provider: o.header.attr("data-provider").toLowerCase(),
videoHeight: o.header.attr("data-video-height"),
videoWidth: o.header.attr("data-video-width")
}, videoDetails
}, d = function () {
o.container.data("aspectRatio", videoDetails.videoHeight / videoDetails.videoWidth), e(window).resize(function () {
var i = e(window).width(), r = e(window).height();
o.container.width(i).height(i * o.container.data("aspectRatio")), r < o.container.height() && o.container.width(i).height(r)
}).trigger("resize")
}, a = function () {
o.videoTrigger.on("click", function (e) {
e.preventDefault(), l(), o.videoCloseTrigger.fadeIn()
}), o.videoCloseTrigger.on("click", function (e) {
e.preventDefault(), s()
})
}, n = function () {
if (Modernizr.video && !f()) {
var e = videoDetails.teaser, i = '<video autoplay="true" loop="loop" muted id="teaser-video" class="teaser-video"><source src="' + e + '.mp4" type="video/mp4"><source src="' + e + '.ogv" type="video/ogg"></video>';
o.container.append(i)
}
}, v = function () {
if ("youtube" === videoDetails.provider)var e = '<iframe id="video" src="http://www.youtube.com/embed/' + videoDetails.id + '?rel=0&hd=1&autohide=1&showinfo=0&autoplay=1&enablejsapi=1&origin=*" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; else if ("vimeo" === videoDetails.provider)var e = '<iframe id="video" src="http://player.vimeo.com/video/' + videoDetails.id + '?title=0&byline=0&portrait=0&color=3d96d2&autoplay=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; else if ("html5" === videoDetails.provider)var e = '<video autoplay="true" loop="loop" id="video"><source src="' + videoDetails.id + '.mp4" type="video/mp4"><source src="' + videoDetails.id + '.ogv" type="video/ogg"></video>';
return e
}, l = function () {
o.header.hide(), o.container.append(v()), c(), o.teaserVideo.hide()
}, s = function () {
e("#video").remove(), o.teaserVideo.fadeIn(), u(), g()
}, c = function () {
o.videoTrigger && o.videoTrigger.fadeOut("slow")
}, u = function () {
o.videoTrigger && o.videoTrigger.fadeIn("slow")
}, g = function () {
o.videoCloseTrigger.hide()
}, f = function () {
return e(window).width() < 900 && Modernizr.touch ? !0 : !1
};
return {init: r}
}(jQuery, document);
Move your jquery code into controller. Using jquery separately outside angular will not work. And also make sure jquery is loaded before angular. It's not good practice to mix jquery with angular then angular can do pretty much everything and come with inbuilt lite jquery.

Start youtube video on hover/mouseover

I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...
I am stuck on the hover command. Can someone help me work it out please?
The page has 16 videos, this is the working code from the jsfiddle that contains 3 videos as an example.
http://jsfiddle.net/sebwhite/gpJN4/
VIDEO:
<iframe id="player" width="385" height="230" src="http://www.youtube.com/embed/erDxb4IkgjM?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0" frameborder="0" allowfullscreen></iframe>
JAVASCRIPT:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
onYouTubeIframeAPIReady();
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
player1.pauseVideo();
player2.pauseVideo();
}
UPDATED FIDDLE
Try this:
var $$ = function(tagname) { return document.getElementsByTagName(tagname); }
function onYouTubeIframeAPIReady() {
var videos = $$('iframe'), // the iframes elements
players = [], // an array where we stock each videos youtube instances class
playingID = null; // stock the current playing video
for (var i = 0; i < videos.length; i++) // for each iframes
{
var currentIframeID = videos[i].id; // we get the iframe ID
players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
// note, the key of each array element will be the iframe ID
videos[i].onmouseover = function(e) { // assigning a callback for this event
if (playingID !== currentHoveredElement.id) {
players[playingID].stopVideo();
}
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].pauseVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
Fiddle:
http://jsfiddle.net/gpJN4/3/

Categories

Resources