How to stop YouTube video when hidding a Div - javascript

I've made a similar question in the past, but I decided to try again since I have gone in a different direction since then. (I was trying with YouTube API and wasn't getting anywhere with that)
I'm trying to build a website where different pages are shown by using a function that hides/shows different divs. One of those pages has a video from YouTube and I was trying to figure out a way to stop the video when the respective div is hidden. Right now, the video just keeps playing in the background (you can hear the sound), if you change to another page/div.
After some sleuthing on the internet (i.e. this website), I finally got a solution working which is as follows.
var stopButton = document.getElementById('fecharvideo');
stopButton.onclick = function() {
var myPlayer = document.getElementById("player");
myPlayer.setAttribute("src", " ");
};
Unfortunately, as you can probably guess. This means that after clicking on an element with the id=fecharvideo, the iframe simply disappears, meaning if you return to that div the video will no longer appear, which is not ideal.
Any similar solution to this problem that allows me to reset the video, instead of deleting it altogether?
Here's the fiddle (To test it out Open "Episódio 1", start video, Open "Episódios" through the hamburger menu, and then back to "Episódio 1"): https://jsfiddle.net/Santos1600/qu8ejwsm/20/

Solution:
html
<div id="ep1" class="ep1" style="display: none;">
<div class="video-background">
<div class="video-foreground">
<iframe id="player" src="https://www.youtube.com/embed/videoseries?list=**PLAYLISTID**&modestbranding=1&iv_load_policy=3&rel=0&showinfo=0&loop=1&autoplay=1&autohide=1&enablejsapi=1&playerapiid=ytplayer1" frameborder="0" allowfullscreen allowscriptaccess="always"></iframe>
</div>
</div>
<div class="container">
<!--Menu/Episódio 1-->
<div id="myNav2" class="overlayep">
<div class="overlay-content">
<ul>
<li>EPISÓDIOS</li>
<ul><li>POEMA MEDRICAS</li>
<li>O CÃO</li>
<li>TERAPIA À DISTÂNCIA</li>
<li>MANIA DA PERSEGUIÇÃO</li>
</ul>
<li>SOBRE</li></ul>
</div>
</div>
<div class="botaomenu" onclick="myFunction(this); toggleNav2();">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<img src="assets/logohorizontal.png" alt="logo" class="logosmall">
</div>
</div>
js
var video1 = document.getElementById('player')
function toggleVideo(a, state) {
var iframe = a.contentWindow;
iframe.postMessage('{"event":"command","func":"' + state + '","args":""}', '*');
}

Related

Wrap Vimeo URL with Player using JS/Regex

I've started developing a site at: http://joshrodg.com/isbellfilms2/
I have a WordPress plugin that generates a pricing table. I like the way the plugin works and functions for the user, but needed to tweak one thing.
The plugin has a place for a description, which I don't have, but I would like to add a video instead.
I recognize this is a WordPress website, but the issue I am having is with my scripting.
What I am trying to do is find the Vimeo URL and pass that into a player.
I found a piece of code, tweaked it a bit, but it's not quite working.
The JS I am using looks like:
<script type="text/javascript">
$(document).ready(function() {
var classSelector = document.querySelectorAll('.rpt_description');
var vimeoRegEx = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
var vimeoEmbed = '<div class="embed-container"><iframe src="https://player.vimeo.com/video/$1" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>';
array.prototype.forEach.call(classSelector, function(el) {
if (vimeoRegEx.test(el.innerHTML)) {
el.innerHTML = el.innerHTML.replace(vimeoRegEx, vimeoEmbed);
}
});
});
</script>
The code the plugin outputs with the Vimeo URLs:
<div class="rpt_plan rpt_plan_ori rpt_plan_0 ">
<div style="text-align: center; height: 15px;" class="rpt_title rpt_title_0">The Family Yearbook Film</div>
<div class="rpt_head rpt_head_0" style="height: 250px;">
<div class="rpt_recurrence rpt_recurrence_0">(Yearly)</div>
<div class="rpt_price rpt_price_0"><span class="rpt_currency"></span>$350</div>
<div style="color:#3ac893;" class="rpt_subtitle rpt_subtitle_0">Stay up to date with your changing family for an entire year.</div>
<div class="rpt_description rpt_description_0">https://www.vimeo.com/320417542</div>
<div style="clear:both;"></div>
</div>
<div class="rpt_features rpt_features_0" style="height: 183px;">
<div style="color:black;" class="rpt_feature rpt_feature_0-0">A 3-5 min film every 3 months (4 total films)</div>
<div style="color:black;" class="rpt_feature rpt_feature_0-1">Plus one Keepsake film</div>
<div style="color:black;" class="rpt_feature rpt_feature_0-2">30% off discount on any additional films you purchase that year.</div>
<div style="color:black;" class="rpt_feature rpt_feature_0-3">Upload 30-450 clips</div>
</div>
<div style="clear:both;"></div>
<a target="_self" href="https://isbellfamilyfilms.com/#order-form" style="background:#3ac893" class="rpt_foot rpt_foot_0">Add to Cart</a>
</div>
The regex finds the URL and the JS takes the URL and passes it to the player, something just isn't quite right. I made sure that this JS executes before the plugin, but I have tried it both ways.
I'm sure I'm missing something simple, any help is appreciated.
Thanks,
Josh
Totally forgot the jQuery reference, so embarrassing! Just needed to add this line before my JS code:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
I also had to capitalize Array
Hope this helps someone!
Josh

How to hide an IFrame on mobile devices

I'm building a website which uses IFrames to play YouTube videos, instead of uploading the raw video as the host doesn't allow large file uploads and it seemed easier to use IFrames. However, how the website works is that when you press a button it opens a div over the top of the rest of the page, like a 'popup' I guess. So this requires that you can hide the IFrame when you close the div.
However, this doesn't work on mobile Chrome of Safari (for iOS10 latest versions). When I try to hide it, the rest of the div hides like normal but the video leaves an impression, as in you can't play it or click anything on the video but it prevents you clicking anything under the video also.
Has anyone encountered any issues like this? Can anyone suggest where my code is wrong?
The website is at http://citm.uk.tn/
Here's the code:
JavaScript:
function fillText(a){
$('#body').load('html/' + a + '.html');
b.style.height = '60vw';
b.style.visibility = 'visible';
ex.style.filter = 'blur(20px)';
ex.style.WebkitFilter = 'blur(20px)';
window.scrollTo(0,0);
}
function wipePop(){
b.style.height = '0';
b.style.visibility = 'hidden';
ex.style.filter = 'none';
ex.style.WebkitFilter = 'none';
frame.style.height = '0';
frame.style.opacity = '0';
}
HTML:
<a class='back' onclick='wipePop()'>Back To Home</a>
<iframe class='video' src="https://www.youtube.com/embed/YXwYJyrKK5A?wmode=opaque" frameborder="0" allowfullscreen id="frame">
</iframe>
More HTML:
<div class='ex' id='ex'>
<div class='banner'><img src='images/full.png' class='full' id='im'></div>
<div class='buttons'><button class='cir' id='1'><img class='buttonimg' src='images/1.png'></button><button class='cir' id='2'><img class='buttonimg' src='images/2.png'></button><button class='cir' id='3'><img class='buttonimg' src='images/3.png'></button><button class='cir' id='4'><img class='buttonimg' src='images/4.png'></button></div>
<div class='videobanner'><button class='vidbanner_l' onclick="fillText('video1')"><img src='images/video.png'></button><button class='vidbanner' onclick="fillText('video2')"><img src='images/video2.png'></button></div>
<br><br><br>
</div>
<div class='body' id='body'>
</div>
I am using jQuery but anything using pure javascript would be prefered. Thanks in advance.

how to stop youtube video playing when container closed

I have seen a few posts about this , but the answers I find are about 1 video and not multiple videos on same page.
I have around 10 videos on my web page. When we click the button for each I want the overlay to pop up which it does. Then a video to be played.
Once the user clicks the exit button I want the video to stop playing.
At the minute if a user does no click pause of the youtube video and exits out it keeps playing in the background.
i will show just 2 video sections for this example:
<div class="play-button">
<i class="fa fa-play"></i>
</div>
<div class="youtube-frame">
<div class="exit-youtube-frame">
<i class="fa fa-times"></i>
</div>
<iframe width="520" height="345" src="<?= $video ?>"></iframe>
</div>
<div class="play-button">
<i class="fa fa-play"></i>
</div>
<div class="youtube-frame">
<div class="exit-youtube-frame">
<i class="fa fa-times"></i>
</div>
<iframe width="520" height="345" src="<?= $video ?>"></iframe>
</div>
Now in Jquery i do this:
jQuery('.play-button').click(function(){
jQuery('#overlay-youtube').show(); // This is the overlay
jQuery(this).next().show();
});
jQuery('.exit-youtube-frame').click(function(){
jQuery(this).parents('.youtube-frame').hide();
jQuery('#overlay-youtube').hide();
});
How do i incorporate method which will stop the video playing for each section?
I had the same problem with showing product videos on a site and stopping them from playing after closing the overlay.
As long as you don't need to pause the video so the user can pick up where they left off, you can simply use the detach() method to store the video object in jQuery then re-add it to the DOM when the user clicks to show it.
Here is my code for just one video (HTML then jQuery):
<div id="product-video-overlay">
<div id="video-container">
<a class="close-overlay">Close</a>
<iframe id="ytplayeroverlay" type="text/html" src="{youtubeURL}"></iframe>
</div>
</div>
var videoOverlay = $('#product-video-overlay');
var videoObject = videoOverlay.find('#video-container');
var hasVideo = 1;
$('li.video-thumb').click(function () {
if (hasVideo == 0) {
videoObject.appendTo(videoOverlay);
}
videoOverlay.fadeIn();
});
$('#product-video-overlay, #product-video-overlay a.close-overlay').click(function (e) {
e.stopPropagation();
videoOverlay.fadeOut();
videoObject.detach();
hasVideo = 0;
});
Since you have multiple videos, you will need some way to identify the play button with its corresponding overlay/video (maybe adding a matching class to each?).
As well, you would probably want to store each detached element into an array to retrieve later by the matching class or whatever method you use to link the button to the proper video.
This is just how I tackled the problem. I know there is a YouTube API available to use, but this did the job.
Good luck!

JavaScript Render Block

Trying to understand how to eliminate or minimize render delay of different JavaScript libraries on a site.
For example, if I want to load the "instant" follow buttons from many Social Networks, they seem to block each other out of rendering and you get unpleasant pop-ins.
<div id="fb-root"></div>
<script>
(function(d, s) {
var j, h = d.getElementsByTagName(s)[0],
f = d.createDocumentFragment(),
add = function(u, i) {
if (d.getElementById(i)) {
return;
}
j = d.createElement(s);
j.src = u;
i && (j.id = i);
f.appendChild(j);
};
add('http://apis.google.com/js/plusone.js');
add('http://connect.facebook.net/en_US/all.js#xfbml=1', 'facebook-jssdk');
add('http://platform.twitter.com/widgets.js', 'twitter-wjs');
add('http://platform.linkedin.com/in.js');
add('http://assets.pinterest.com/js/pinit.js');
h.parentNode.insertBefore(f, h);
}(document, 'script'));
</script>
<div id="wrapper" style="width:100%; max-width:800px; margin-left:auto; margin-right:auto; text-align:center;">
<div id="widgetWrapper" style="width:100%; max-width:800px; background-color: #eee; padding: 10px; margin-left:auto; margin-right:auto;">
<div class="followBox">
<div class="fb-like" data-href=" " data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div>
</div>
<div class="followBox">
<div class="g-follow" data-annotation="bubble" data-height="20" data-href=" " data-rel="author"></div>
</div>
<div class="followBox">
Follow
</div>
<div class="followBox">
<div class="g-ytsubscribe" data-channel=" " data-layout="default" data-count="default"></div>
</div>
<div class="followBox">
<iframe class="btn" frameborder="0" border="0" scrolling="no" allowtransparency="true" height="25" width="113" src="http://platform.tumblr.com/v1/follow_button.html?button_type=2&tumblelog= &color_scheme=dark"></iframe>
</div>
<div class="followBox">
<script type="IN/FollowCompany" data-id=" " data-counter="right"></script>
</div>
<div class="followBox">
<a data-pin-do="buttonFollow" href="http://www.pinterest.com/ /">Fun Paw Care</a>
</div>
</div>
</div>
What can be done about this type of render blocking from JS in general? Not specifically just social network buttons, they just provide the best example.
You have very little control over your code this way.
You're actually calling to five different sites in order to load and run their code. If only one site will be a little busy you'll end up in a delayed display on your site.
There are workarounds for this problem and you can see examples almost everywhere.
There are some solutions available:
Homemade social buttons - you create and draw your own icons and attach the external site code 'under the hood'. It may seems like a simple solution but the last time I checked, it involved editing not-so-small lines of code. Personally I'd advise this as a last resort.
One button to rule them all - You probably saw it on other pages, a small sharing button that expand into a box with all you favorite social sites. These come pre-made and are an easy solution.
Patient is virtue - you warp all your links in a hidden container and display it after all renderings are done. The user will see the buttons appear together a few seconds after the site loads.
And keep in mind that javascript has a pretty much one track mind. Even if all your code was stored locally it still would take turns to render all of it.

Javascript on Multiple DIVs

I am using a Wordpress Theme (Incipiens) that has a show/hide Javascript to show a map on the contact page http://demo.themedev.me/wordpress_themes/incipiens/contact-us/
I want to use this function on a page multiple times to show/hide galleries.
<div class="map">
<div class="map_top">
<hr class="toolbox toolbox1">
</div>
<hr class="vertical_sep0">
<a class="show_map" href="javascript:void(0)"></a>
<div class="map_container"><div class="thismap"><iframe>........</iframe></div>
</div>
I have this working but the call to the js opens all divs. I therefore put a unique div id round each gallery and slightly changed the javscript...
<div class="map">
<div class="map_top">
<hr class="toolbox toolbox1">
</div>
<hr class="vertical_sep0">
<div id="silestone">
<div class="map_container">
[show_gallery width="124" height="124" galleryid="527"][/show_gallery]
</div>
</div>
</div>
It works but very oddly, sometimes the right one opens, sometimes the wrong one...not sure what i'm doing wrong, should I just have one javascript call that contains the ID's to all divs? If so how do I do this?
Since you have not shown the actual script you use for toggling, I assume you mean something like this (taken from the page) -
function (){
$(this).toggleClass('hide_map');
$('.map_container').slideToggle(400);
}
I would change that to -
function unhide(id){
$(this).toggleClass('hide_map');
$('#' + id).find('.map_container').slideToggle(400);
}
Does that work?

Categories

Resources