Video player still playing after closing modal - javascript

HTML:
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="color:white;">×</button>
</div>
<div class="modal-body">
<video id='videoPlayer' width="100%" height="100%" controls="controls">
<source id='mp4Source' src="" type="video/mp4" />
<!--<source id='oggSource' src="movie.ogg" type="video/ogg" />-->
</video>
</div>
</div>
</div>
</div>
</div>
JS
function play(i){
var x = document.getElementById("hidden_"+i).value;
var player = document.getElementById('videoPlayer');
var mp4Vid = document.getElementById('mp4Source');
player.pause();
// Now simply set the 'src' property of the mp4Vid variable!!!!
mp4Vid.src = x;
player.load();
$('#myModal').modal('show');
}
I play a video inside the modal but when I click out side of the modal before the video completes the modal will hide but the the video continues to play

You can use the event hide.bs.modal. Check the documentation here.
$('#myModal').on('hide.bs.modal', function(){
player.pause();
})

$('#myModal').on('hidden.bs.modal', function (e) {
player.pause();
})

Related

How to dynamically play video based on the button to clicked

Hello I have a 2 buttons trailer and movie, I want to play the video based on the button I clicked.
For example I choose Trailer then it should play trailer and vice versa
here is my button
<button class="btn btn-sm btn-dark" id="trailer" data-toggle="modal" data-target="#myModal2">Trailer</button>
<button class="btn btn-sm btn-dark" id="movieNoads" data-toggle="modal" data-target="#myModal2">Movie</button>
here is my video player and its javascript codes
<video controls playsinline id="player" width="100%">
<script type="text/javascript">
var video = document.getElementById('video');
var source = document.createElement('source');
document.getElementById('trailer').onclick = function () {
source.setAttribute('src', '../inflightapp/storage/app/public/trailer_videos/<?php echo ''.$row2['trailer_video'].''; ?>');
video.appendChild(source);
video.play();
}
document.getElementById('movieNoads').onclick = function () {
source.setAttribute('src', '../inflightapp/storage/app/public/movie_videos/<?php echo ''.$row2['movie_video'].''; ?>');
video.appendChild(source);
video.play();
}
</script>
</video>
You forgot to load the video
"use strict";
console.clear();
const video = document.getElementById("player");
const source = document.createElement("source");
function loadVideo(element, src) {
source.src = src;
element.appendChild(source);
element.load();
element.play();
}
document.getElementById("trailer").addEventListener(
'click',
() => loadVideo(
video,
"https://s3-us-west-2.amazonaws.com/s.cdpn.io/96344/lego.mp4"
)
)
document.getElementById("movieNoads").addEventListener(
'click',
() => loadVideo(
video,
"https://s3-us-west-2.amazonaws.com/s.cdpn.io/96344/abstract-001.mp4"
)
)
<button class="btn btn-sm btn-dark" id="trailer" data-toggle="modal" data-target="#myModal2">Trailer</button>
<button class="btn btn-sm btn-dark" id="movieNoads" data-toggle="modal" data-target="#myModal2">Movie</button>
<video controls playsinline id="player" width="100%" loop></video>
You can have a look at this.
<button class="btn btn-sm btn-dark" id="trailer">Trailer</button>
<button class="btn btn-sm btn-dark" id="movieNoads">Movie</button>
<script type="text/javascript">
var trailer = document.getElementById('trailer');
trailer.setAttribute('data-toggle', 'modal');
trailer.setAttribute('data-target', '#myModal2');
var movieNoads = document.getElementById('movieNoads');
movieNoads.setAttribute('data-toggle', 'modal');
movieNoads.setAttribute('data-target', '#myModal2');
</script>
<video controls playsinline id="player" width="100%">
<script type="text/javascript">
var video = document.getElementById('player');
document.getElementById('trailer').onclick = function () {
document.getElementById("player").style.display = "block";
video.setAttribute('src', 'YouVideoURLHere');
video.play();
}
document.getElementById('movieNoads').onclick = function () { document.getElementById("player").style.display = "block";
video.setAttribute('src', 'YourVideoURLHere');
video.play();
}
document.getElementById("player").style.display = "none";
</script>
</video>
You Can try this
function setvideo(src) {
document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style=" width: 100%;"><source src="'+src+'" type="video/mp4"></video>';
document.getElementById('video_ctrl').play();
}
<!DOCTYPE html>
<html>
<body>
<div id="div_video"> </div>
<button onClick="setvideo('movie.mp4')"> Trailer</button>
<button onClick="setvideo('mov_bbb.mp4')"> Movie</button>
</body>
</html>
Welcome to Stack Overflow. You could try something along the lines of the following:
I used jQuery and Bootstrap (as I noticed you used Bootstrap HTML elements).
//Custom function to populate a modal. This could be expanded on to even add a destination parameter in order to use seperate modals (e.g. function videoModal(destination, source) and replace #myModal2 with the `destination` parameter).
function videoModal(source) {
$("#myModal2 .modal-body").html($("video#player").clone());
//Add your second source:
$("#myModal2 video#player > source").attr("src", source);
$("#myModal2 .modal-body video#player").css("display", "block");
}
$(document).ready(function() {
//On init, save current loaded state of modal
let modalInit = $("#myModal2 .modal-body").html();
//On interaction with a control
$("body").on("click", "button#trailer", function() {
//Populate modal
videoModal("https://www.w3schools.com/tags/movie.mp4");
});
$("body").on("click", "button#movieNoads", function() {
//Populate modal
videoModal("https://www.w3schools.com/html/mov_bbb.mp4")
});
//Reset modal on close
$("#myModal2").on('hidden.bs.modal', function(e) {
$("#myModal2 .modal-body").html(modalInit);
});
});
video#player {
display: none;
margin-left: auto;
margin-right: auto;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<video id="player" controls autoplay loop>
<source src="" type="video/mp4">
</video>
<!-- Button trigger modal -->
<button type="button" id="trailer" class="btn btn-primary" data-toggle="modal" data-target="#myModal2">
Trailer
</button>
<button type="button" id="movieNoads" class="btn btn-primary" data-toggle="modal" data-target="#myModal2">
Movie
</button>
JSFiddle
This way you could also load the videos inside modals (as I noticed you were trying to use modal buttons). No refreshes are required.

How to stop a youtube video after modal is dismissed?

After closing modal window the i frame element keeps playing and I don't have a clue how to refer to proper element in JS.
The trick is that I use PHP variable as an ID to generate and use multiple modal windows straight from my database.
The code goes as follows:
foreach ($movieId as $data) {
echo '<div class="card card-movie-poster bg-blacker text-white text-center text-align-middle mx-2 mb-3">
<div class="card-body">
<a data-toggle="modal" href="#myModal'.$data['movieID'].'"><img class="card-img " src="img/movieCovers/'.$data['datatitle'].'.jpg"></a>
</div>
</div>';}
And
foreach ($movieId as $datatitle) {
echo '<div class="modal fade" id="myModal'.$data['movieID'].'">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content bg-black">
<div class="modal-header">
<!-- Movie Title -->
<h3 class="text-white-50">'.$data['movieTitle'].'</h3>
<!-- Close button -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body container">
<!-- Video -->
<div class="embed-responsive embed-responsive-16by9">
<iframe id="'.$data['movieID'].'" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/'.$data['videoUrl'].'?rel=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
';}
You can try:
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
OK then.
Finally did it myself:
var grabbed = document.querySelectorAll('[id^="myModal"]');
var myModal;
var innerIframe;
for (var i = 0; i < grabbed.length; i++) {
// console.log(grabbed[i].id);
$(grabbed[i]).on('show.bs.modal', function () {
myModal = this.id;
// console.log(this.id);
})
$(grabbed[i]).on('hide.bs.modal', function () {
// console.log(this.id + " closed");
innerIframe = this.getElementsByClassName('embed-responsive-item');
$('iframe').attr('src', $('iframe').attr('src'));
// console.log(innerIframe[0]);
});
}

Bootstrap carousel - pause/Stop the YouTube video while sliding next slide in model box

I have Twitter Bootstrap modal box with carousel multiple slide videos and images. I am adding a YouTube Video to my Twitter Bootstrap carousel. Problem is it moves next slide video still playing in background so I want to stop/pause it on the next/prev slide.
Also i need to stop YouTube Video when close Twitter Bootstrap modal box
I have search around SO but didn't find similar question.
Try this code
$("video").each(function () { this.pause() });
$('#myCarousel').carousel({
interval: 0
});
$('.carousel-control.left').click(function() {
$('#myCarousel').carousel('prev');
});
$('.carousel-control.right').click(function() {
$('#myCarousel').carousel('next');
$("video").each(function () { this.pause() });
});
$('button.close').click(function(){
$("video").each(function () { this.pause() });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<div class="row">
<div class="span4 offset4">
<a class="btn" data-toggle="modal" href="#myModal" >Launch Modal</a>
</div>
</div>
<div class="modal fade hide" id="myModal" data-keyboard="true">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div id="myCarousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item">
<video width="400" controls>
<source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
<div class="item">
<img src="http://placehold.it/300x200/aaa&text=Item 2" />
</div>
<div class="item">
<img src="http://placehold.it/300x200/444&text=Item 3" />
</div>
</div>
</div>
<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</div>
function createVideo(video) {
var youtubeScriptId = 'youtube-api';
var youtubeScript = document.getElementById(youtubeScriptId);
var videoId = video.getAttribute('data-video-id');
if (youtubeScript === null) {
var tag = document.createElement('script');
var firstScript = document.getElementsByTagName('script')[0];
tag.src = 'https://www.youtube.com/iframe_api';
tag.id = youtubeScriptId;
firstScript.parentNode.insertBefore(tag, firstScript);
}
window.onYouTubeIframeAPIReady = function() {
window.player = new window.YT.Player(video, {
videoId: videoId,
playerVars: {
autoplay: 1,
modestbranding: 1,
rel: 0
}
});
}
}
posted by mehaboob from digitalizing india
$(function() {
$('.carousel').on('slide.bs.carousel',function(e){
var prev = $(this).find('.active').index();
var next = $(e.relatedTarget).index();
var video = $('#video-player')[0];
var videoSlide = $('#video-player').closest('.carousel-item').index();
if (next === videoSlide) {
createVideo(video);
}
});
});

Have a youtube video stop after popopping up as an overlay

Here is some code where when you click on a link/image, an embedded youtube video is revealed as an overlay, similar to a lightbox effect.
When I have one video set up, the video will stop playing when I click on the 'x' to closer the popup/overlay.
If I add more videos, the video continues to play in the background. The overlay is hidden but the audio still runs.
Can you help me find out how to stop the video? I need a total of 6 videos on a page.
HTML:
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<a onclick="startoverlay()" href="#" title="Watch video" class="flex-item box-link bg-lightgrey fg-darkgrey">
<div class="tiled-image" id="img0">
<div class="tiled-overlay">
<h3 class="sm-title hblack text-uppercase"><strong class="fg-white"> <span class="fa fa-play" aria-label="Play"></span> </strong></h3> </div>
</div>
<div class="tiled-body">
<p>text</p>
</div>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<a onclick="startoverlay2()" href="#" title="Watch video" class="flex-item box-link bg-lightgrey fg-darkgrey">
<div class="tiled-image" id="img0">
<div class="tiled-overlay">
<h3 class="sm-title hblack text-uppercase"><strong class="fg-white"> <span class="fa fa-play" aria-label="Play"></span> </strong></h3> </div>
</div>
<div class="tiled-body">
<p>text</p>
</div>
</a>
</div>
Overlays:
<!-- VIDEO ONE OVERLAY-->
<div id="overlay" class="modal" role="dialog" aria-labelledby="modal-video-label">
<div class="modal-dialog modal-full" role="document">
<div class="modal-content">
<div class="modal-header text-right">
<button type="button" class="close" id="close-button" onclick="startoverlay()" aria-label="Close"> <span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body">
<div class="modal-video">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="video" class="embed-responsive-item" src="https://www.youtube.com/embed/6HOlHZfqzxk?enablejsapi=1" frameborder="0"></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- VIDEO TWO OVERLAY-->
<div id="overlay2" class="modal" role="dialog" aria-labelledby="modal-video-label">
<div class="modal-dialog modal-full" role="document">
<div class="modal-content">
<div class="modal-header text-right">
<button type="button" class="close" id="close-button" onclick="startoverlay2()" aria-label="Close"> <span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body">
<div class="modal-video">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="video" class="embed-responsive-item" src="https://www.youtube.com/embed/o1aVMcrb4aE?enablejsapi=1" frameborder="0"></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="modal-backdrop" class="modal-backdrop fade in"></div>
JavaScript:
For the second part of the script I have duplicated the overlay code and called it startoverlay2 - I am not sure if that is correct.
<script type="text/javascript">a
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('video', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
var pauseButton = document.getElementById('close-button');
pauseButton.addEventListener('click', function() {
player.pauseVideo();
});
}
var tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
<!-- /* overlays */ -->
<!-- /* OVERLAY 1 */ -->
<script type="text/javascript">
function startoverlay() {
el = document.getElementById("overlay");
el.style.display = (el.style.display == "block") ? "none" : "block";
els = document.getElementById("modal-backdrop");
els.style.display = (els.style.display == "block") ? "none" : "block";
}
</script>
<!-- /* OVERLAY 2 */ -->
<script type="text/javascript">
function startoverlay2() {
el = document.getElementById("overlay2");
el.style.display = (el.style.display == "block") ? "none" : "block";
els = document.getElementById("modal-backdrop");
els.style.display = (els.style.display == "block") ? "none" : "block";
}
</script>
I do wonder if I need to do something to the pauseButton var?
To resolve this, it looks like you need to tell the video to stop playing. As you're using the iframe version of the YouTube player, we can do this by replacing it's src tag with the same value.
// get the video's surrounding overlay
el = document.getElementById("overlay");
// hide the overlay, or show it if it's already hidden
el.style.display = (el.style.display == "block") ? "none" : "block";
// Restart the video (paused)
var videoIFrame = el.querySelector('iframe');
srcUrl = videoIFrame.getAttribute('src');
videoIFrame.setAttribute('src', srcUrl);
This causes the video to be reloaded, taking you back to the (paused) start state, ready for the modal to be opened again.
If you want to pause the video in its current place, you'll want to consider using the API rather than the iframe option.
It's a bit outside the scope of the question, but there's also some refactoring you could do to reduce the code repetition, for example pulling the JS into a single 'hide' function:
function stopAndHide(element) {
element.style.display = "none";
// Restart the video (paused)
var videoIFrame = element.querySelector('iframe');
srcUrl = videoIFrame.getAttribute('src');
videoIFrame.setAttribute('src', srcUrl);
els = document.getElementById("modal-backdrop");
els.style.display = "none";
}
and then calling it from the HTML as follows:
<button type="button" class="close" onclick="stopAndHide(this)" aria-label="Close"> <span aria-hidden="true">×</span> </button>

Stop the video from playing

I have two videos on the same page and they open in an iframe. When I close the popup, the video won't stop. It keeps playing. Due to circumstances beyond my control, I have to work with the videos within iframes.
Could anyone help, below is the code for the same:
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";
document.getElementById("vid1").style.top = top + "px";
document.getElementById("vid1").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="popup" id="media-popup"> <!-- video embedded -->
<iframe id="vid" src="http://player.vimeo.com/video/1212121210?title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe class="show-2" style="display: none;" id="vid1" src="http://player.vimeo.com/video/112324343?title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<a class="video-close" href="#0"></a>
</div><!-- popup -->
<a id="video" data-media="//www.vimeo.com/134243242">video 1</a>
<a id="video" class="video-2" data-media="//www.vimeo.com/00102102">Video 2</a>
This helped me, check it out!
click here to go to the original answer
Basically you need to use iframe or video to start player and that code will stop it when you want it.
var stopVideo = function ( element ) {
var iframe = element.querySelector( 'iframe');
var video = element.querySelector( 'video' );
if ( iframe !== null ) {
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
if ( video !== null ) {
video.pause();
}
};
To stop the video, not only pause it, you can set currentTime to 0 like:
video.pause()
video.currentTime = 0
This will 'reset' the src attribute for each iframe, stopping the video.
jQuery("iframe").each(function() {
var url = jQuery(this).attr('src');
jQuery(this).attr('src', url);
});
You can also run the following if the iframe is within your domain.
jQuery('iframe').contents().find('video').each(function ()
{
this.pause();
});
jQuery('video').each(function ()
{
this.pause();
});
http://plnkr.co/edit/BWPfY8PiYagfb1zIHUEV?p=preview
This plunker helped me to achieve the solution to my question.
HTML:
<head>
<title>Autostop Videos in Closed Modal</title>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link rel="stylesheet" href="style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Autostop Videos in Closed Modal</h1>
<ul class="nav" >
<li>Video 1</li>
<li>Video 2</li>
</ul>
<div class="modal fade" id="video1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" >
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video 1</h4>
</div>
<div class="modal-body">
<iframe src="//player.vimeo.com/video/108792063" width="500" height="300" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="modal fade" id="video2">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" >
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video 2</h4>
</div>
<div class="modal-body">
<iframe src="//player.vimeo.com/video/69593757" width="500" height="300" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</body>
</html>
JS:
$(function(){
$('.modal').on('hidden.bs.modal', function (e) {
$iframe = $(this).find("iframe");
$iframe.attr("src", $iframe.attr("src"));
});
});

Categories