Embedded Video keeps playing even after closed - javascript

I have a video which would keep playing even after I close it.
I feel there is something I am missing in my jQuery.
Could anyone please help me.
Below is the code related to it.
Jquery
$("[data-media]").on("click", function(e) {
e.preventDefault();
var $this = $(this);
var videoUrl = $this.attr("data-media");
var popup = $this.attr("href");
var $popupIframe = $(popup).find("iframe");
$popupIframe.attr("src", videoUrl);
var left = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var left = left/2 - 340;
var top = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var top = top/2 - 180
document.getElementById("vid").style.top = top + "px";
document.getElementById("vid").style.left = left + "px";
$this.closest(".page").addClass("show-popup");
});
$(".popup").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$(".page").removeClass("show-popup");
});
$(".popup > iframe").on("click", function(e) {
e.stopPropagation();
});
HTML
<div class="page"> <!-- class "page" is required for video to work-->
<div class="popup" id="media-popup"> <!-- video embedded -->
<iframe id="vid" src="http://testvideo.com" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div><!-- popup -->
</div>

You have a list of video url when you click one, a popup comes up showing the corresponding video.When you are done with that video you want to remove it by clicking outside the iframe but inside popup.
Here is the problem
You are using this $(".page").removeClass("show-popup");
to get the second part done removing this class will simply hide it using css display orvisibility it's like making something invisible but still you can hear it, so video is invisible but it's still there playing .To fix this you need to wipe the src of iframe
$('.page iframe').attr("src", '');

Related

I need to open 4 Bootstrap modals (4.1 version) and autoplay a different Vimeo video on each one of them

I've been using this solution by Franceso Borzi:
var videoSrc = $("#myModal iframe").attr("src");
$('#myModal').on('show.bs.modal', function () { // on opening the modal
// set the video to autostart
$("#myModal iframe").attr("src", videoSrc+"&autoplay=1");
});
$("#myModal").on('hidden.bs.modal', function (e) { // on closing the modal
// stop the video
$("#myModal iframe").attr("src", null);
});
FYI: This snippet can be found on this thread: Bootstrap Modals & Youtube: Autoplay and Stop on Close:
It works when there is only one Vimeo video on the page. When I try to open a different video for each modal, the modals only play the latest video on the markup.
This is my code so far:
<div class="modal" data-modal-window id="modal-vimeo-01">
<iframe id="v01" src="https://player.vimeo.com/video/726139458?h=02e309cac8" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>
<button data-modal-close class="close" data-dismiss="modal" aria-label="Close"><i class="icofont-close-circled"></i></button>
</div>
<div class="modal" data-modal-window id="modal-vimeo-02">
<iframe id="v02" src="https://player.vimeo.com/video/723317173?h=8ce2334289" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>
<button data-modal-close class="close" data-dismiss="modal" aria-label="Close"><i class="icofont-close-circled"></i></button>
</div>
<script>
var videoSrc = $("#modal-vimeo-01 iframe").attr("src");
$('#modal-vimeo-01').on('show.bs.modal', function () { // on opening the modal
// set the video to autostart
$("#modal-vimeo-01 iframe").attr("src", videoSrc+"&autoplay=1");
});
$("#modal-vimeo-01").on('hidden.bs.modal', function (e) { // on closing the modal
// stop the video
$("#modal-vimeo-01 iframe").attr("src", null);
});
</script>
<script>
var videoSrc = $("#modal-vimeo-02 iframe").attr("src");
$('#modal-vimeo-02').on('show.bs.modal', function () { // on opening the modal
// set the video to autostart
$("#modal-vimeo-02 iframe").attr("src", videoSrc+"&autoplay=1");
});
$("#modal-vimeo-02").on('hidden.bs.modal', function (e) { // on closing the modal
// stop the video
$("#modal-vimeo-02 iframe").attr("src", null);
});
</script>
I'm quite new to JS and Jquery, so any help would be much appreciated.
Thanks!
You problem will be most likely that you have 4 modals/videos that have the same class or id. Since I can't see your code I can't tell you where your mistake is, but that will be the problem for sure.
You should try it with having 4 id`s for your modals (like #modal1, #modal2, etc.) and and make sure that you select the correct video source, which you do in the first line:
var videoSrc = $("#myModal iframe").attr("src");
You would need something like
$("#modal1 iframe")
$("#modal2 iframe")
$("#modal3 iframe")
$("#modal4 iframe")
If this is not helping you, then you need to post your code. Because the code you posted is fine.
EDIT:
You are reacreating / overriding the videoSrc variable. You need to use unique names for these.
var videoSrc1 = $("#modal-vimeo-01 iframe").attr("src");
var videoSrc2 = $("#modal-vimeo-02 iframe").attr("src");
var videoSrc3 = $("#modal-vimeo-03 iframe").attr("src");
var videoSrc4 = $("#modal-vimeo-04 iframe").attr("src");
The problem is with the scope of videoSrc
You set the value to src of the iframe of the first video
Then in the second script, you redefine videoSrc to be the src of the second iframe
The scope of videoSrc in both cases is the same.
These are equivalent:
- var videoSrc = “someUrl”;
- window.videoSrc = “someUrl”
So in your second script, videoSrc gets overwritten.
Each modal should have its own uniquely named source variable.
Edit: in order to handle this properly, you would do something like this:
var firstModalSrc = $(firstModalID iframe).attr(src)
$(firstModalID).on(…)
var secondModalSrc = $(secondModalID iframe).attr(src)
$(secondModalD).on(…)
…

Add video to page on Button click

I am a beginner JS user, and I am trying to get a video to play on fullscreen and replace an invisible div further down on the page. I started with a guide from Chris Ferdinandi.
In his guide, the video replaces the image that is clicked. I would like to have the div later down on the page to be replaced on the click.
Any guidance would be great!
HTML
<a data-video="480459339" class="stylsheetref" href="#" target="">Watch the Tour</a>
<div id="video-replace"></div>
Javascript (modified from this guide)
<script>
if (!Element.prototype.requestFullscreen) {
Element.prototype.requestFullscreen = Element.prototype.mozRequestFullscreen || Element.prototype.webkitRequestFullscreen || Element.prototype.msRequestFullscreen;
}
// Listen for clicks
document.addEventListener('click', function (event) {
//Set invisible Div (new code added by me)
var videonew = '#video-replace');
// Check if clicked element is a video link
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="560" height="960" src="https://player.vimeo.com/video/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, videonew);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
</script>
There are problems in your code.
var videonew = '#video-replace'); there's an orphan ), since you are using this in the `replaceChild``method I assume you want the variable to reference to an element.
So change it to
var videonew = document.querySelector('#video-replace');
Pro tip: Using the Developer console during development can help you figure out such errors in your code.

How do I autoplay a video after clicking on an image?

I am using the below code in a WordPress editor. With my current code when I click on the image the actual video shows up, and I have to click the video again to play it.
I want to change it so that an image of the video is displayed and when I click on that the video should start to play. I just have to click once. Right now I have to click twice which is bad user experience. This is required to reduce page load time.
<div class="youtube" id="PpMS2SP_3Fs" style="width:100%; height: 600px;"></div>
<script>
var videos = document.getElementsByClassName("youtube");
for (var i = 0; i < videos.length; i++) {
var youtube = videos[i];
var img = document.createElement("img");
img.setAttribute("src", "https://www.sociosquares.com/wp-content/uploads/2019/04/vid-img1-opti.jpg");
img.setAttribute("class", "thumb");
var circle = document.createElement("div");
circle.setAttribute("class", "circle");
youtube.appendChild(img);
youtube.appendChild(circle);
youtube.onclick = function() {
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.id + "?autoplay=1&loop=1&playlist=PpMS2SP_3Fs");
//"https://www.youtube.com/embed/PpMS2SP_3Fs?autoplay=1&loop=1&playlist=PpMS2SP_3Fs");
iframe.style.width = this.style.width;
iframe.style.height = this.style.height;
this.parentNode.replaceChild(iframe, this);
};
}
</script>
I expected the video to autoplay after a click on the image, but it doesn't, and I have to click again to play the video.
jQuery('#image_id').click(function() {
jQuery(".youtube").attr('src', jQuery(".youtube", parent).attr('src') + '?autoplay=1');
});
image_id is your image element id you are clicking and youtube is the class of the iframe your embed has.

Use $(window).scroll function to jump to divs on a page

Im trying to mimic the functionality of this site https://moto360.motorola.com/
When you scroll down on that page it just jumps to the next "screen" and if you scroll up it jumps back up.
My JS is here :
var currentDiv = "Home";
var latestScroll = 0;
var scrollable = true;
$(document).ready(function(){
$("#HomeLink").addClass("activeNav");
$(".navLink").click(function(){
$(".navLink").removeClass("activeNav");
$(this).addClass("activeNav");
var divID = $(this).attr("data-linkID");
scrollTo(divID);
});
$(window).scroll(function(){
console.log(scrollable);
if (scrollable==true){
var currentScroll = $(window).scrollTop();
if (currentScroll > latestScroll){
scrollable = false;
//downscroll
if(currentDiv!="About"){
var nextDiv = $("#"+currentDiv).next()[0];
var nextDivID = $(nextDiv).attr("id");
scrollTo(nextDivID);
}
}else{
scrollable = false;
//upscroll
if(currentDiv!="Home"){
var prevDiv = $("#"+currentDiv).prev()[0];
var prevDivID = $(prevDiv).attr("id");
scrollTo(prevDivID);
}
}
}
});
});
function scrollTo(divID){
currentDiv = divID;
var target = $("#"+divID);
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
setTimeout(function() {
// Do something after 2 seconds
latestScroll = target.offset().top;
scrollable = true;
}, 2000);
}
My problem is that once it starts scrolling it jumps to the next screen but then when the jQuery animate is running it registers more scrolls and then just keeps jumping. I've tried adding the boolean scrollable and even a timeout when setting that back to true but it still will jump at least twice.
HTML :
<div id="screens">
<div class="screen" id="Home">
<div id="logo">ZEPPA</div>
</div>
<div class="screen" id="Video">
<iframe width="100%" height="100%" src="http://www.youtube.com/embed/XGSy3_Czz8k"></iframe>
</div>
<div class="screen" id="Info">INFO</div>
<div class="screen" id="About">ABOUT US</div>
</div>
Anyone have any ideas on how to fix this? I cannot seem to find a way to get it to only register the scrolling once and then reset itself nicely.
I have a fiddle here: http://jsfiddle.net/a1cpx2cf/
I would recommend you to make use of a tested plugin like fullPage.js rather than trying to reinvent the wheel.
Things will become more complicated when you start worrying about touch screen computers, mobile phones, kinetic scrolling (used in Apple laptops), transitions performance, fallback compatibility with old browsers, keyboard accessibility, changes in the URL for each section, useful URLs for returning users or specific linking etc.
Using a tested script will always make things easier and will save you many headaches.

Bootstrap Modal Window not recognize all the variations of YouTube URLs

On the Internet I found a jQuery code that works very well to open YouTube video in modal form. I change some dteails and everything was fine until I realized that do not recognize all the variations of YouTube URLs.
All I need is to extract the YouTube ID and put it in the right place. I wrote a regex and combined several versions but does not work with every URL.
This is my code:
$('a[href^="https://www.youtu"]').on('click', function(e){
var YouTube=$(this).attr('href').replace(/feature=player_embedded[&\w]*(?!['"][^<>]*>|<\/a>)/ig, "").replace(";", ""); // replace player_embedded
preg=/(?:http|https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w\-]{10,12})\b[?=&\w]*(?!['"][^<>]*>|<\/a>)/ig,
youtubeID=YouTube.replace(preg, '$1');
if (youtubeID!="" && (YouTube.indexOf('v') > -1 || YouTube.indexOf('embed') > -1))
{
// Prevent opening of external page
e.preventDefault();
// Variables for iFrame code. Width and height from data attributes, else use default.
var width = $(window).width(),
vidWidth = 800, // default
vidHeight = 450; // default
if ( $(this).attr('data-width') ) { vidWidth = parseInt($(this).attr('data-width')); }
if ( $(this).attr('data-height') ) { vidHeight = parseInt($(this).attr('data-height')); }
// responsive debug
var vidWidth = (width>vidWidth?800:(width-60));
var iFrameCode = '<div class="video-container"><iframe width="' + vidWidth + '" height="'+ vidHeight +'" scrolling="no" allowtransparency="true" allowfullscreen="true" src="https://www.youtube.com/embed/'+ youtubeID +'?controls=0&autohide=1&autoplay=1&iv_load_policy=3&theme=light&rel=0&showinfo=0" frameborder="0"></iframe></div>';
// Replace Modal HTML with iFrame Embed
$('#mediaModal .modal-body').html(iFrameCode);
// Set new width of modal window, based on dynamic video content
$('#mediaModal').on('show.bs.modal', function () {
// Add video width to left and right padding, to get new width of modal window
var modalBody = $(this).find('.modal-body'),
modalDialog = $(this).find('.modal-dialog'),
newModalWidth = vidWidth + parseInt(modalBody.css("padding-left")) + parseInt(modalBody.css("padding-right"));
newModalWidth += parseInt(modalDialog.css("padding-left")) + parseInt(modalDialog.css("padding-right"));
newModalWidth += 'px';
// Set width of modal (Bootstrap 3.0)
$(this).find('.modal-dialog').css('width', newModalWidth);
});
// Open Modal
$('#mediaModal').modal();
}
});
Thanks!

Categories