How to stop youtube video programmatically in jQuery - jquery-mobile

I'm developing a simple web application with jQueryMobile, I can swipe between different pages with Youtube videos,
the problem I have is quite simple, I want to stop a youtube video whine I swipe go to the next page,
otherwise the user will have two youtube videos playing in the same time.
here is the Code and the demo :
JSFiddle DEMO + FULL CODE
Here is my awesome full code :
var i =1;
$("body").on("swipeleft",function(){
if (i<2) {
i++;
$.mobile.changePage('#p'+i, {
transition: "slide"
});
}
});
$("body").on("swiperight",function(){
if (i>1) {
i--;
$.mobile.changePage('#p'+i, {
transition: "slide",
reverse: true
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div data-role="page" id="p1">
<iframe width="560" height="315" src="https://www.youtube.com/embed/X9_n8jakvWU" frameborder="0" allowfullscreen></iframe>
</div>
<div data-role="page" id="p2">
<iframe width="560" height="315" src="https://www.youtube.com/embed/UecPqm2Dbes" frameborder="0" allowfullscreen></iframe>
</div>

Given the older version of jQuery you are using, I assume you are using jQuery Mobile 1.3 not 1.4.
You could use the pagebeforehide event to get the iframe of the page you are leaving and then quickly set the src of the iframe to nothing and then back to the video url. This will stop the video from playing.
var TheFrame;
$(document).on( "pagebeforehide", function( event, data ) {
TheFrame = $(event.target).find("iframe");
setTimeout(StopVideo, 500);
});
function StopVideo(){
var vid = TheFrame.prop("src");
TheFrame.prop("src", "");
TheFrame.prop("src", vid);
}
The setTimeout allows the slide transition to complete before messing with the iframe src.
Working DEMO
If you are using jQM 1.4, you can use the pagecontainer widget events instead:
var TheFrame;
$(document).on( "pagecontainerbeforehide", function( event, ui ) {
TheFrame = ui.prevPage.find("iframe");
setTimeout(StopVideo, 500);
});
function StopVideo(){
var vid = TheFrame.prop("src");
TheFrame.prop("src", "");
TheFrame.prop("src", vid);
}

Related

Using Youtube API for stop video by playing another one

I'm trying to stop emebed youtube video when another one is played on the same page, I found this:
stackoverflow
fiddle-example
But when i try to use it on my web page it doesn't work:
my_test
SCRIPT
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var $ = jQuery;
var players = [];
$('iframe').filter(function(){return this.src.indexOf('http://www.youtube.com/') == 0}).each( function (k, v) {
if (!this.id) { this.id='embeddedvideoiframe' + k }
players.push(new YT.Player(this.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
$.each(players, function(k, v) {
if (this.getIframe().id != event.target.getIframe().id) {
this.pauseVideo();
}
});
}
}
}
}))
});
}
</script>
HTML
One:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed /zXV8GMSc5Vg?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"> </iframe>
<br/>
Two:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/LTy0TzA_4DQ?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"> </iframe>
What's wrong? I've created the project on google developers, i've created the API key but i don't know where i must put that.
You forgot to add the jquery lib ( https://code.jquery.com/ )
SOLVED
The problem was that in the example they used the "origin" parameter, this parameter if setted avoids the introduction into the page of malicious third-party JavaScript code, which can take control of the YouTube player.
src="http://www.youtube.com/embed/LTy0TzA_4DQ?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net"
This is why the code work on the fiddle page but not on mine.
So i've changed this origin path with my complete URL of the host page and now it work!

Target a specific iframe ID?

I have a page that has multiple youtube videos. I want the video to play when someone clicks on the link that corresponds to each video.
For Example: When someone clicks on the video 2 link, video 2 plays.
HTML
<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>
<iframe id="ytplayer" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
frameborder="0"></iframe>
Video 1
<br><hr>
<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>
<iframe id="ytplayer2" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/WdkT4_OJ2WU?enablejsapi=1"
frameborder="0"></iframe>
Video 2
JQUERY
var ytplayer;
function onYouTubeIframeAPIReady() {
ytplayer = new YT.Player('ytplayer', {
});
}
$(document).ready(function () {
$("#start").click(function () {
ytplayer.playVideo();
});
});
HERE IS MY JSFIDDLE Only clicking on video 1 works.
Here is a demo that works as you expected.
I have removed the second script tag and modified the ids of the second iframe and a tags.
var ytplayer, ytplayer2;
function onYouTubeIframeAPIReady() {
ytplayer = new YT.Player('ytplayer', {});
ytplayer2 = new YT.Player('ytplayer2', {});
}
$(document).ready(function () {
$("#start").click(function () {
ytplayer.playVideo();
return false;
});
$("#start2").click(function () {
ytplayer2.playVideo();
return false;
});
});
The html part:
<!-- This loads the YouTube IFrame Player API code -->
<script src="http://www.youtube.com/player_api"></script>
<iframe id="ytplayer" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
frameborder="0"></iframe>
Video 1
<br><hr>
<iframe id="ytplayer2" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/WdkT4_OJ2WU?enablejsapi=1"
frameborder="0"></iframe>
Video 2
Hope this helps.

Twitter timeline widget resets iframe content after jquery-ui toggle effect

After googling and analyzing DOM, i found out:
iframe dynamically replaces twitter's timeline a-link
jquery-ui effects force iframe to reload content
similar question
sample at jsfiddle
html
click here to start toggle
<div id="panel">
<a id="twitter-widget" class="twitter-timeline" href="https://twitter.com/search? q=%23Globallogic" data-widget-id="418408420543184896">#Globallogic</a>
</div>
css
#panel {
background:gray;
width:640px;
height:512px;
}
js
!function(d,s,id){var js,fjs=d.getElementsByTagName(s) [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
$( window ).mousedown(function() {
$( "#panel" ).toggle( "slide", { direction: "left" }, 1000 );
});
Is it possible to configure jquery-ui to avoid iframe reload? and I'm appreciated for any other suggestions.
You can use the following code to reload the twitter widget's content:
twttr.widgets.load()
Be sure to run it after the widget has initially loaded as it will throw up an error otherwise.
I just encountered this issue and I resolved it by dynamically loading child elements to the panel
and ask twitter to load the widget. To do this , if below is you twitter div
then
<div id="panel">
<a id="twitter-widget" class="twitter-timeline" href="https://twitter.com/search?q=%23Globallogic"
data-widget-id="418408420543184896">#Globallogic</a>
</div>
Please place the below java script anywhere using the script tags.
window.twttr = (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f) {
t._e.push(f);
};return t;
}(document, "script", "twitter-wjs"));
Use setInterval() call the update function. In this function you can remove the existing twitter iframe ( created at the time of loading) , and replace it with your original link. after this is done simply call twttr.widgets.load() a standard event given by twitter
$(function(){
function updateStatus(){
var $twitter = $("#panel");
$twitter.append(" <a id='twitter-widget'
class='twitter-timeline' href='https://twitter.com/search?
q=%23Globallogic' data-widget- id='418408420543184896'>#Globallogic</a>");
twttr.widgets.load();
};
setInterval(function(){updateStatus()}, 1000);
});
Tweets that have images may take some time to load.

How do videos autoplay on iOS at youtube.com

When I set autoplay to true for a YouTube video (IFrame API) on my site, it doesn't work. All the documentation says apple disables autoplay on ios for bandwidth reasons.
However, I see that videos play automatically (without clicking on the video element) on youtube.com on iPad. How did YouTube make it work? It would be hard to imagine Apple does something special just for YouTube.
It seems that Youtube's team uses the interaction of the user when taps/clicks a video button to authorize the reproduction.
Remember that youtube.com is a SPA (Single Page Application) so there is no page reload or redirection.
So, youtube.com doesn't have autoplay enabled.
You can do it with javascript.
Here is an example:
<div class="video-container">
<div id="player"> </div> <!--<iframe width="960" height="720" src="//www.youtube.com/embed/5YptIh_avrM?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>-->
</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: '720',
width: '960',
videoId: 'YOUR_ID_HERE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
event.target.setVolume(20);
}
// 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) {
}
function stopVideo() {
player.stopVideo();
}
</script>
I stumbled into similar but more complicated issue/requirement.
I need to show YouTube video on a modal popup. Popup is shown on a click.
Have taken YouTube API code (From https://developers.google.com/youtube/iframe_api_reference) and modified a bit to work with Bootstrap popup.
Below is my code
<div class="modal" id="videoModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="videoWrapper">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"> </div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// 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: '360',
width: '640',
videoId: 'YOUR VIDEO ID',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
//event.target.playVideo();// Nullifying the action otherwise the video will play as soon as page loads
}
// 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();
}
function ShowPopup() {
$('#videoModal').modal('show');
player.playVideo();
}
//Stop video when bootstrap popup is closed
$("#videoModal").on('hide.bs.modal', function () {
player.stopVideo();
});
</script>
It can't be done. For various reasons (including, but not limited to data usage), Apple doesn't allow auto-playing of videos.
Please refer to:
Youtube embedded video: autoplay feature not working in iphone
I haven't tested this, but you may be able to use Javascript and call the play function for the player, or even just click the element when the page has loaded.

Sencha Touch2 Stop YouTube video when I go to another page

How can I stop or pause a YouTube Video from playing when I go to another page
In Sencha Touch2 Here is my code it seems like it should work but Video still plays.
Ext.define('MyApp.view.tablet.Home5', {
extend: 'Ext.Panel',
xtype: 'home5',
config: {
scrollable: true,
cls:'logo',
items:[
{
xtype: 'panel',
id: 'videopanel',
html:[
'<div id="video1"><iframe width="560" height="315" src="http://www.youtube.com/embed/NSUucup09Hc?fs=1&hl=en_US&rel=0&autoplay=0" frameborder="0" allowfullscreen></iframe></div>',
'<img src="resources/images/thapelo3Fy.jpg" />'
].join("")
}
]
},
hide: function(container, options){
this.callParent(arguments);
//workaround to stop the video (= reset the html)
Ext.getCmp('videopanel').setHtml("");
Ext.getCmp('videopanel').setHtml('<div id="video1"><iframe width="560" height="315" src="http://www.youtube.com/embed/NSUucup09Hc?fs=1&hl=en_US&rel=0&autoplay=0" frameborder="0" allowfullscreen></iframe></div><img src="resources/images/thapelo3Fy.jpg" />');
}
});
How can I stop a video with Javascript in Youtube? is what you need to do. Would have typed it here, but on my mobile...

Resources