Jquery make Youtube video stop playing when clicking outside popup - javascript

I have this Jquery popup where I store an iframe with a youtube video. When I click the link, the popup opens and the User can click on the video and play it. Even though, when I click outside the popup, the popup closes, but the video/sound keeps playing! How can I avoid this?
Here's my HTML
CLICK
<div class="bg" style="display:none"></div>
<div class="popup" style="display:none">
<iframe width="480" height="360" src="//www.youtube.com/embed/Q_WHGV5bejk" frameborder="0" allowfullscreen></iframe>
</div>
my JS:
$(function(){
$("#showPopup").click(function(e){
e.stopPropagation();
$(".bg").toggle();
$(".popup").toggle();
});
$("body").click(function(){
$(".bg").toggle();
$(".popup").hide();
});
});
And the CSS:
.popup{
background-color:#E6E9F2;
position:absolute;
min-height:auto;
width:auto;
border: solid 2px #B9EAF0;
z-index: 1002;
}
.bg {
background-color:#111;
opacity: 0.65;
position:absolute;
z-index: 1000;
top:0px;
left:0px;
width:100%;
min-height:100%;
overflow:auto;
}
I alos created a Fiddle http://jsfiddle.net/nLBZa/6/
so, does anyone have a suggestion?
thanks in advance...

Try adding the following into your Jquery
$('#playerID').get(0).stopVideo();
EDIT:
OK, so I thought that would work according to the API, anyways... Here is another solution:
var video = $("#player").attr("src");
$("#player").attr("src","");
$("#player").attr("src",video);
and your fiddle updated.

Assume, I have several different YT videos embedded in CSS only modals, like this:
<div id="video1" class="modalDialog">
<div>
X
<div id="video1_content"><iframe width="420" class="yvideo" id="video1_iframe" height="315" src="https://www.youtube.com/embed/_Qc4V_vEXdY?rel=0&showinfo=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe></div>
</div>
I can dynamically unload (and therefor stop playing) a single video like so:
$('.videoclose').click(function( e ){
var contentdiv = $(this).next('div');
var iframe = $(contentdiv).find('iframe:first');
var video = $(iframe).attr("src");
$(iframe).attr("src","");
$(iframe).attr("src",video);
});
Thanks to Mike for the ignition ;-)

Related

Iframe loading spinner/progress bar using javascript

I have an iframe which is referencing a Google Sheets tab, and its quite slow loading. I'm looking to have a spinner graphic or loader % progress bar (even more ideal) whilst the iframe is loading. Would you know an approach for this using Javascript and/or CSS please?
No need to use jquery for this. If you would like to use an actual progress bar, you'd have to use ajax to load the content.
function closeIndicator(){
var s = document.getElementById('spinner');
console.log(s);
s.style.display = "none";
}
#spinner{
z-index:99999;
position:absolute;
top: 0;
left: 0;
}
<iframe id="documentIFrame" onload="closeIndicator()" src="https://stackoverflow.com/" >
</iframe>
<img id="spinner" src="spinnder.gif" />
If jQuery is an option. -> Not perfectly styled but I hope you get the idea.
$('#myIframe').on('load', function(){
$('#loader').fadeOut();
});
iframe {
height:500px;
width:500px;
}
#loader {
position:absolute;
height:500px;
width:500px;
background:#000;
margin-top:-500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe src="https://www.brotherops.com" id="myIframe"></iframe>
<div id="loader"><img src="https://i.giphy.com/media/FaAxdPWZ7HKGmlnku7/giphy.webp" alt="Loading" /></div>

Select everything except iframe by using $(this) and .not

I have wrote this code and it is working properly:
HTML:
<div class="service-box">
<!--Services Title 1-->
<h3>WordPress installation</h3>
<!--Content for title 1-->
<div class="service-content">
<!--Your youtube service video iframe code-->
<iframe width="420" height="315" src="https://www.youtube.com/embed/R7hHfoffIM4?rel=0" frameborder="0" allowfullscreen></iframe>
<!--Your service description-->
<p>I am offering services like:</p>
<p>WordPress installation to your already purchased domain and hosting.</p>
<p>Also I am able to create subdomain and install wordpress on it.</p>
<p>If You need me to make a WP backup, I can do that for You.</p>
<p>In case that You need me to restore your website from my previously made backup I am here for You.</p>
</div>
JS:
$(document).on('click', '.service-box', function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html()); //I will change this line
$('body').css('overflow', 'hidden');
});
Then I try to select everything except IFRAME tag like this:
$('#popupWindow #contentBox').html($(this).not($('iframe')).html());
or like this:
$('#popupWindow #contentBox').html($(this).not('iframe').html());
and it doesn't work.
I have also tried to use:not selector in all combinations like this:
$('#popupWindow #contentBox').html($(this:not).html());
Nothing is working. Is there anyone who knows the answer to this?
Thanks!
You want to remove the iframe from the html of the clicked element, not from the clicked element itself. so.... you'll have to clone it and remove it from the clone, then append it.
var clone = $(this).clone();
clone.find('iframe').remove();
$('#popupWindow #contentBox').html(clone.contents());
Is this what you want?
var clone = $(this).clone();
clone.find('iframe').remove();
$('#contentBox').empty().append(clone);
$(document).on('click', '.service-box', function() {
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
var clone = $(this).clone();
clone.find('iframe').remove();
$('#contentBox').empty().append(clone);
$('body').css('overflow', 'hidden');
});
#siteOverlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0,0,0,0.5);
}
#siteOverlay.overlay-active {
display: block;
}
#popupWindow {
position: absolute;
top: 50px;
left: 50px;
right: 50px;
bottom: 50px;
background-color: white;
padding: 50px;
overflow-y: scroll;
}
#contentBox {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="service-box">
<!--Services Title 1-->
<h3>WordPress installation</h3>
<!--Content for title 1-->
<div class="service-content">
<!--Your youtube service video iframe code-->
<iframe width="420" height="315" src="https://www.youtube.com/embed/R7hHfoffIM4?rel=0" frameborder="0" allowfullscreen></iframe>
<!--Your service description-->
<p>I am offering services like:</p>
<p>WordPress installation to your already purchased domain and hosting.</p>
<p>Also I am able to create subdomain and install wordpress on it.</p>
<p>If You need me to make a WP backup, I can do that for You.</p>
<p>In case that You need me to restore your website from my previously made backup I am here for You.</p>
</div>
</div>
<div id="siteOverlay">
<div id="popupWindow">
<div id="contentBox"></div>
</div>
</div>

Can't pause video on closing popup

The problem is that, when I close the popup without pausing the video, the audio keeps playing. I cannot pause the video while closing the popup. The complete code is give below.
//html code
<style>
.yourModalClass {
padding: 0 1.5em 1em;
border-radius: 5px;
max-width: 380px;
color:#fff;
}
.yourModalClass a {
color:#fff;
}
</style>
abc
<div id="yourModalId" class="yourModalClass" style="display:none; margin-left: -20%; margin-right: 20%">
<h2>abc</h2>
<video width="600" height="400" controls="">
<source src="abc.mp4" type="video/mp4"/>
Your browser does not support HTML5 video.
</video>
</div>
<script>
$('#yourModalId').modality({
effect: 'slide-up'
});
</script>
//javascript
/* #author: Himanshu Kandpal (cse10324.sbit#gmail.com)*/
;(function(e,t,n,r){var i="modality",s=e("body")[0],o= {autoBind:true,clickOffToClose:true,closeOnEscape:true,effect:"",innerClass:"mm-wrap",modalClass:"modality-modal",onClose:"",onOpen:"",openClass:"mm-show",openOnLoad:false,userClass:""},u=function(t,n){var r=this;r.defaults=o;r.id=e(t).attr("id");r.settings=e.extend({},o,n);r.$modal=e(t).wrap('<div class="'+r.settings.modalClass+" "+r.settings.effect+" "+r.settings.userClass+'">'+'<div class="'+r.settings.innerClass+'">'+"</div>"+"</div>").show();r.$wrapper=r.$modal.parents("."+r.settings.modalClass);r.$triggers=e('a[href="#'+r.id+'"], [data-modality="#'+r.id+'"]');if(r.settings.autoBind){r.$triggers.each(function(){r.setTrigger(e(this))})}if(r.settings.clickOffToClose){r.$wrapper.click(function(e){e.preventDefault();if(e.target==r.$wrapper[0])r.close()})}if(r.settings.closeOnEscape){e(s).keyup(function(e){if(e.keyCode==27)r.close()})}if(navigator.appVersion.indexOf("MSIE 7.")!=-1){r.$wrapper.prepend('<div class="mm-ghost"></div>')}if(r.settings.openOnLoad)r.open();return r};e.extend(u.prototype,{open:function(e){this.$wrapper.add(s).addClass(this.settings.openClass);if(typeof this.settings.onOpen=="function")this.settings.onOpen();if(typeof e=="function")e();return this},close:function(e){this.$wrapper.add(s).removeClass(this.settings.openClass);if(typeof this.settings.onClose=="function")this.settings.onClose();if(typeof e=="function")e();return this},toggle:function(e){return this.isOpen()?this.close(e):this.open(e)},isOpen:function(){return this.$wrapper.hasClass(this.settings.openClass)},setTrigger:function(e){var t=this;e.click(function(e){e.preventDefault();t.toggle()});return t}});e.extend(u,{instances:{},init:function(e,t){var n={},i=this,s=0;e.each(function(){var e=new i(this,t);i.instances[e.id]=n[s]=e});return n[1]===r?n[0]:n}});e[i]=u;e.fn[i]=function(t){return e[i].init(this,t)}})(jQuery,window,document);
add id to the video controler element
call after slide up
$('#videoID')[0].pause();
$("#videoID")[0] will return you the DOM element not the jQuery object as the pause method is not the jquery method its the DOM method

Can't Stop YouTube Video in Hidden DIV Playing in the background

I've tried various things but can't get a YouTube video in a hidden DIV to stop playing in the background before the DIV toggle is even clicked. visibility:hidden didn't seem to solve the issue. Here's the code I'm using. Hope someone can help! I can turn off autoplay to solve it, but then it means users have to click an extra button (the YouTube 'play' button) which isn't ideal.
** IN THE OF THE WEB PAGE:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".productDescription").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".productDescription").slideToggle();
return false;
});
});
</script>
** IN THE BODY:
<div class="productDescription">
<iframe width="715" height="440" src="http://www.youtube.com/embed/BLbTegvRg0U?&wmode=transparent&autoplay=0" frameborder="0" allowfullscreen></iframe>
<div class="closebutton">Close Video
</div>
</div>
** AND IN THE STYLESHEET:
.productDescription {
display: block;
position:absolute;
left:0px;
top:-2px;
z-index:5;
background-color: #000;
margin: 0px;
float: left;
padding: 0px;
width: 715px;
min-height: 600px;
height: 600px;
}
.show_hide {
display:none;
}
.closebutton {
display: block;
width:120px;
height: 22px;
position:absolute;
left:20px;
top:50px;
background-color: #000;
padding-top: 3px;
float: left;
z-index: 9999;
}
Thanks very much in advance!
The autoplay feature will start to play the video once it is loaded, whether the div is visible or hidden.
However, if you remove the autoplay setting, you can then use a YouTube API to control the video so that the video will start playing when a person clicks to show the div. One option is the iframe API (which I would recommend since you are already using iframe to embed the video, and this allows YouTube to serve up an HTML5 video rather than a flash video if the viewer is on a mobile device) and another option is the JavaScript API.
Because you asked for more details, here is a quick explanation of how to use the YouTube iFrame API to meet your needs. I recommend reading the documentation so you can understand what is going on and adapt it as needed.
First, in your HTML create your iframe video the same way you did above, but add two things: an ID for the iframe and an origin parameter in the iframe src. (The origin parameter helps keep you YouTube player safe from javascript hacking.) So it would look like this:
<iframe id="player" width="715" height="440" src="http://www.youtube.com/embed/BLbTegvRg0U?&wmode=transparent&autoplay=0&origin=http://example.com/" frameborder="0" allowfullscreen></iframe>
Replace the example.com url with the website this page will be on.
Somewhere after the iframe, but before the </body> tag, add this code to load the api and initialize the player:
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player');
}
</script>
Then, in your javascript, just before the line that reads $('.productDescription').slideToggle(), add this code:
if ($('.productDescription').is(':visible')) {
player.pauseVideo();
}
else {
player.playVideo();
}
This code will test to see whether the .productDescription div is visible. If it is hidden, it will start the video and display the div. If it is not visible, it will pause the video and hide the div.
That should do it.
I have same issue, but I could fix with this.Refer to YouTubeAPI,we can't implement directly.So I edit this way.
Step1: Creat loadYTScript() function and put youtubeAPI code,
Step2: is call function onYouTubeIframeAPIReady()
Then at onclick call the load function.
Here is your js code:
function loadYTScript(){
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
jQuery(document).ready(function() {
$('.show_hide').click(function(){
$(".productDescription").slideToggle();
loadYTScript();
});
});
At html don't forget to add
<div class="productDescription">
<div id="player"></div>
</div>
Hope it work well.

How to display loading message when an iFrame is loading?

I have an iframe that loads a third party website which is extremely slow to load.
Is there a way I can display a loading message while that iframe loads the user doesn't see a large blank space?
PS. Note that the iframe is for a third party website so I can't modify / inject anything on their page.
I have done the following css approach:
<div class="holds-the-iframe"><iframe here></iframe></div>
.holds-the-iframe {
background:url(../images/loader.gif) center center no-repeat;
}
I think that this code is going to help:
JS:
$('#foo').ready(function () {
$('#loadingMessage').css('display', 'none');
});
$('#foo').load(function () {
$('#loadingMessage').css('display', 'none');
});
HTML:
<iframe src="http://google.com/" id="foo"></iframe>
<div id="loadingMessage">Loading...</div>
CSS:
#loadingMessage {
width: 100%;
height: 100%;
z-index: 1000;
background: #ccc;
top: 0px;
left: 0px;
position: absolute;
}
If it's only a placeholder you are trying to achieve: a crazy approach is to inject text as an svg-background. It allows for some flexbility, and from what I've read the browser support should be fairly decent (haven't tested it though):
Chrome >= 27
FireFox >= 30
Internet Explorer >= 9
Safari >= 5.1
html:
<iframe class="iframe-placeholder" src=""></iframe>
css:
.iframe-placeholder
{
background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 100% 100%"><text fill="%23FF0000" x="50%" y="50%" font-family="\'Lucida Grande\', sans-serif" font-size="24" text-anchor="middle">PLACEHOLDER</text></svg>') 0px 0px no-repeat;
}
What can you change?
Inside the background-value:
font size: look for font-size="" and change the value to anything you want
font color: look for fill="". Don't forget to replace the # with %23 if you're using hexadecimal color notation. %23 stands for a # in URL encoding which is necessary for the svg-string to be able to be parsed in FireFox.
font family: look for font-family="" remember to escape the single quotes if you have a font that consists of multiple words (like with \'Lucida Grande\')
text: look for the element value of the text-element where you see the PLACEHOLDER string. You can replace the PLACEHOLDER string with anything that is url-compliant (special characters need to be converted to percent notation)
Example on fiddle
Pros:
No extra HTML-elements
No js
Text can easily (...) be adjusted without the need of an external program
It's SVG, so you can easily put any SVG you want in there.
Cons:
Browser support
It's complex
It's hacky
If the iframe-src doesn't have a background set, the placeholder will shine through (which is not inherent to this method, but just standard behaviour when you use a bg on the iframe)
I would only recommend this only if it's absolutely necessary to show text as a placeholder in an iframe which requires a little bit of flexbility (multiple languages, ...). Just take a moment and reflect on it: is all this really necessary? If I had a choice, I'd go for #Christina's method
An alternative solution.
<iframe srcdoc="Loading..." onload="this.removeAttribute('srcdoc')" src="https://example.com"></iframe>
Note that srcdoc attribute can have any HTML markup. So you can apply custom styles to the message.
<iframe id="example" src="https://example.com"></iframe>
<script>
const iframe = document.getElementById('example');
iframe.srcdoc = '<!DOCTYPE html><p style="color: green;">Loading...</p>';
iframe.addEventListener('load', () => iframe.removeAttribute('srcdoc'));
</script>
Here's a quick solution for most of the cases:
CSS:
.iframe-loading {
background:url(/img/loading.gif) center center no-repeat;
}
You can use an animated loading GIF if you want to,
HTML:
<div class="iframe-loading">
<iframe src="http://your_iframe_url_goes_here" onload="$('.iframe-loading').css('background-image', 'none');"></iframe>
</div>
Using the onload event you can remove the loading image after the source page is loaded inside your iframe.
If you are not using jQuery, just put an id into the div and replace this part of code:
$('.iframe-loading').css('background-image', 'none');
by something like this:
document.getElementById("myDivName").style.backgroundImage = "none";
All the best!
$('iframe').load(function(){
$(".loading").remove();
alert("iframe is done loading")
}).show();
<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>
Yes, you could use a transparent div positioned over the iframe area, with a loader gif as only background.
Then you can attach an onload event to the iframe:
$(document).ready(function() {
$("iframe#id").load(function() {
$("#loader-id").hide();
});
});
You can use below code .
iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}
I have followed the following approach
First, add sibling div
$('<div class="loading"></div>').insertBefore("#Iframe");
and then when the iframe completed loading
$("#Iframe").load(function(){
$(this).siblings(".loading-fetching-content").remove();
});
<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo - IFRAME Loader</title>
<style>
#frameWrap {
position:relative;
height: 360px;
width: 640px;
border: 1px solid #777777;
background:#f0f0f0;
box-shadow:0px 0px 10px #777777;
}
#iframe1 {
height: 360px;
width: 640px;
margin:0;
padding:0;
border:0;
}
#loader1 {
position:absolute;
left:40%;
top:35%;
border-radius:20px;
padding:25px;
border:1px solid #777777;
background:#ffffff;
box-shadow:0px 0px 10px #777777;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="frameWrap">
<img id="loader1" src="loading.gif" width="36" height="36" alt="loading gif"/>
<iframe id="iframe1" src="https://bots.actcorp.in/ACTAppChat/chat?authtext=test#user8.com&authToken=69d1afc8d06fb97bdb5a9275edbc53b375c3c7662c88b78239ba0cd8a940d59e" ></iframe>
</div>
<script>
$(document).ready(function () {
$('#iframe1').on('load', function () {
$('#loader1').hide();
});
});
</script>
</body>
</html>
You can use as below
$('#showFrame').on("load", function () {
loader.hide();
});

Categories