29

I am creating a website with bootstrap that can be found here - http://www.branchingouteurope.com/digital-spark-testing/

If you select the video image you'll see a modal window open a youtube video. The problem I have is that when the modal window is closed the video keeps playing. I want this video to stop when the modal window is closed.

I've looked online and read many solutions however none seem to work. Here is the mark up...

<span class="main_video">
<div data-toggle="modal" data-target="#myModal" style="cursor:pointer">
<img src="img/master/video.fw.png" height="81%" width="60%" alt="Digital Spark Video"/>
</div>
</span>

<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  </div>
  <div class="modal-body">
  <iframe width="100%" height="100%" src="//www.youtube.com/embed/sIFYPQjYhv8?rel=0" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

`

Stephen Tamlin
  • 295
  • 1
  • 3
  • 8

16 Answers16

25

Here's a little bit lighter of an answer based on dizarter's version and one of the solutions he links to.

$('#modal-video').on('hidden.bs.modal', function () {
    $("#modal-video iframe").attr("src", $("#modal-video iframe").attr("src"));
});
Cloudkiller
  • 1,616
  • 3
  • 18
  • 26
21

Testing here in FireFox 26.0, works as expected. When I either close the Modal or click outside of it and then re-open it - video is back to start and stopped.

EDIT 1

Reproduced in Chrome, the video indeed keeps playing after the Modal is closed.

Try these already answered questions

Stop a youtube video with jquery?

Twitter Bootstrap Modal stop Youtube video

The best way seems to be to use YouTube API to stop the video. Answer that uses this method is available in the questions above.

EDIT 2

This solution seems to be working.

First, get the JS from this post: YouTube iframe API: how do I control a iframe player that's already in the HTML? and include it on the page.

Add this JS after you have loaded the above script (just before the closing body tag)

<script type="text/javascript">
    $('#myModal').on('hidden.bs.modal', function () {
        callPlayer('yt-player', 'stopVideo');
    });
</script>

You will also need to add an ID to the div containing the iframe, as below

<div class="modal-body" id="yt-player">
    <iframe src="//www.youtube.com/embed/sIFYPQjYhv8?rel=0&enablejsapi=1" allowfullscreen="" width="100%" frameborder="0" height="100%"></iframe>
</div>
Community
  • 1
  • 1
dizarter
  • 448
  • 1
  • 8
  • 21
15

This solution works fine for Boostrap 4. It supports many different modals on the same page without specifying modal id. Here is the demo http://jsfiddle.net/hxtpoe/6k09f4x2/

$('.modal').on('hide.bs.modal', function() {
     var memory = $(this).html();
     $(this).html(memory);
});
Łukasz
  • 623
  • 5
  • 12
  • This is brilliant! The other answers that require resetting the iframe src will not work properly if the modal contains more than one video. (after closing the modal and reopening it the iframe might load a wrong link) This is a much more brilliant way of preventing the src of the iframe being loaded incorrectly when modal contains more than one video! – hiew1 Jul 22 '20 at 00:11
  • 1
    Awesome @Łukasz! I used this @ https://forwardemail.net but optimized it so modals won't get changed unless there's an ` –  Feb 02 '21 at 17:16
14

take a look at my code I did not need to use any API

// on preview show iframe
$('#myModalPrev').on('show.bs.modal', function (e) {
  var idVideo = $(e.relatedTarget).data('id');
  $('#myModalPrev .modal-body').html('<iframe width="100%" height="400px" src="https://www.youtube.com/embed/' + idVideo + '?autoplay=true" frameborder="0" allowfullscreen></iframe>');
});
//on close remove
$('#myModalPrev').on('hidden.bs.modal', function () {
   $('#myModalPrev .modal-body').empty();
});

HTML

<a href="#" data-id="5Kp_1Vq6pRg" data-target="#myModalPrev" data-toggle="modal">Abrir Modal</a>
    <div class="modal fade" id="myModalPrev" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 id="myModalLabel" class="semi-bold">Visualizar <strong>Marca</strong>.</h4>
                    </div>
                    <hr>
                    <div class="modal-body">
                        Modal Content
                    </div>
                    <hr>
                    <div class="modal-footer">
                        <button type="button" data-dismiss="modal" class="btn btn-primary"><i class="fa fa-times"></i> Fechar</button>               
                    </div>
                </div>
            </div>
        </div>

Demo : https://jsfiddle.net/o0ftdvs1/

Bruno Ribeiro
  • 1,280
  • 16
  • 21
7

Way simpler easier inspired by @Łukasz per https://stackoverflow.com/a/52315492/3586413 with live demo @ https://forwardemail.net.

//
// any modals with embedded <iframe> we can assume need reset
// <https://stackoverflow.com/a/52315492>
//
$('body').on('hide.bs.modal', '.modal', function() {
  const $modal = $(this);
  // return early if there were no embedded YouTube videos
  if ($modal.find('iframe').length === 0) return;
  const html = $modal.html();
  $modal.html(html);
});
5

Here is an alternative to CloudKiller's answer that actually works with autoplay, just change .attr to .removeAttr like so:

jQuery('#myModal iframe').removeAttr("src", jQuery("#myModal iframe").removeAttr("src"));

But an even more minified/simplified version of this is to simply replace the src with an empty value:

$('#myModal iframe').attr('src', '');

So the only code that you need to add for this to work is:

jQuery('#myModal').on('hidden.bs.modal', function (e) {
    $('#myModal iframe').attr('src', '');
});
Danny Mahoney
  • 1,255
  • 2
  • 13
  • 24
3

And if like me you want the video's to autoplay, then getting them to stop when you click close on the Bootstrap modal you need to do something like this:

$('.modal-iframe-youtube').click(function (e) {
        e.preventDefault();
        var sitetypeHref = $(this).attr('href');
        var sitetypeHrefAuto = sitetypeHref + "?autoplay=1"
        //sitetypeHref = sitetypeHref.replace('watch?v=', 'v/');
        $('#modal-window-iframe-youtube').on('shown.bs.modal', function () {
            var iFrame = $(this).find("iframe");
            iFrame.attr("src", sitetypeHrefAuto);
        });
        $("#modal-window-iframe-youtube").on('hidden.bs.modal', function () {
            var iFrame = $(this).find("iframe");
            iFrame.attr("src", sitetypeHref);
        });
        $('#modal-window-iframe-youtube').modal({ show: true });
    });

Notice that I am adding the "?autoplay=1" arg dynamically. Hope that helps someone.

Perry
  • 611
  • 6
  • 15
2

To write efficient code, first of all we need to check on DOM ready that iframe is exist or not if exist so go to next level otherwise don't do anything. I have used catching also.

$("#myModal").on("hidden.bs.modal", function() {

    var _this = this,
        youtubeSrc = $(_this).find("iframe").attr("src");

    if($(_this).find("iframe").length > 0){                     // checking if there is iframe only then it will go to next level
        $(_this).find("iframe").attr("src", "");                // removing src on runtime to stop video
        $(_this).find("iframe").attr("src", youtubeSrc);        // again passing youtube src value to iframe
    }
}
Anand Deep Singh
  • 2,560
  • 3
  • 22
  • 28
2

This is a solution that worked for me (a bit hacky though):

First, I wrapped my iframe with a div named "VideoId" like this:

<div id="VideoId" style="position: relative; padding: 25px; height: 0;">
    <iframe style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;"
    src="//www.youtube.com/etc..."
    frameborder="0" 
    allowfullscreen>
    </iframe>
</div>

Then i made this function:

function CloseVideo(){
    document.getElementById("VideoId").innerHTML="&nbsp;";
};

And finally, on the closing my Panel button (it was a modal in my case) i added an oncklick event calling my function, like this:

<button type="button" class="btn pull-right" onclick="CloseVideo();" data-dismiss="modal">Back</button>

Of course, if you want to call it again, you have to refill the contents of VideoId with javascript as follows:

document.getElementById("VideoId").innertHTML=
 '<iframe style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;"+
    'src="//www.youtube.com/etc..."'+
    'frameborder="0"'+ 
    'allowfullscreen>'+
    '</iframe>';

It works perfectly in Chrome, Firefox, IE and Opera.

P.S. I tried to empty the div directly from the onclick calling, but it kept reporting a missing bracket, - i don't know why...

parouden
  • 1
  • 2
parouden
  • 21
  • 1
2

Very simple code to place in your footer:

<script language="javascript" type="text/javascript">

    $(function(){
            $('.close').click(function(){      
                    $('iframe').attr('src', $('iframe').attr('src'));
    });
            });
</script>
2

you can use youtube API to Stop(player.stopVideo()) or pause (player.pauseVideo()) your video. here the example code.

HTML

Place this markup in your modal content.

<div id="player"></div>

Load youtube API and initialize player

 var tag = document.createElement('script');

  tag.src = "https://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', {
          height: '390',
          width: '640',
          videoId: 'N8c20YDDHd8',
        });
      }

Stop or pause Video on modal close

     $('#videoModal').on('hidden.bs.modal', function (e) {
        // player.stopVideo();
        player.pauseVideo()
    });
patelarpan
  • 7,188
  • 2
  • 20
  • 25
1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Embedding YouTube Video inside Bootstrap Modal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style type="text/css">
    .bs-example{
        margin: 20px;
    }
    .modal-content iframe{
        margin: 0 auto;
        display: block;
    }
</style>
<script type="text/javascript">
$(document).ready(function(){
    /* Get iframe src attribute value i.e. YouTube video url
    and store it in a variable */
    $("#myModal").modal('show');
    var url = $("#cartoonVideo").attr('src');

    /* Assign empty url value to the iframe src attribute when
    modal hide, which stop the video playing */
    $("#myModal").on('hide.bs.modal', function(){
        $("#cartoonVideo").attr('src', '');
    });

    /* Assign the initially stored url back to the iframe src
    attribute when modal is displayed again */
    $("#myModal").on('show.bs.modal', function(){
        $("#cartoonVideo").attr('src', url);
    });
});
</script>
</head>
<body>
<div class="bs-example">
    <!-- Button HTML (to Trigger Modal) -->
    <a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a>

    <!-- Modal 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">×</button>
                    <h4 class="modal-title">YouTube Video</h4>
                </div>
                <div class="modal-body">
                    <iframe id="cartoonVideo" width="560" height="315" src="https://www.youtube.com/embed/LGWqUVFrfU4?autoplay=1&modestbranding=1&autohide=1&showinfo=0&controls=0" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>     
</body>
</html>     

use this code check once again. it works for me nicely.

DSK
  • 492
  • 5
  • 13
1

If you have several video modals, the best way to handle it without resorting to use the api is this:

$('#myModal').on('hidden.bs.modal', function (e) {
  var $iframes = $(e.target).find('iframe');
  $iframes.each(function(index, iframe){
  $(iframe).attr("src", $(iframe).attr('src'));
  });
})

This goes through all the iframes on your modals and resets them, instead of overwriting the src of all your iframes to the first video on your modal set.

0

when popup open add iframe dynamic in div and when close popup clear div data ex: add

$('#divifream').html('your ifream');

when popupclose

$('#divifream').html('');

this work for me.

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
danish
  • 21
  • 1
0

A simple working example can be found here.

   $("#myModal").on('hidden.bs.modal', function (e) {
    $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
Ritchie
  • 408
  • 3
  • 11
  • Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. You can use the edit link below your answer to improve the post. – BDL Oct 19 '20 at 08:18
  • let me try to explain, when you close your modal it updates the video source to its origional/previous state before you play it. – Ritchie Oct 19 '20 at 11:17
  • @Richie: Edit your answer to explain that. – BDL Oct 19 '20 at 11:31
0

Bootstrap 4 & 5 - YouTube iFrame

Stop video when modal is closed and have video ready to be played when opened again.

$('#yourModalID').on('hide.bs.modal', function(e) {    
   var $if = $(e.delegateTarget).find('iframe');
   var src = $if.attr("src");
   $if.attr("src", '/empty.html');
   $if.attr("src", src);
});

And simply add the ID to your Modal (in this case #yourModalID). Example:

<div class="modal" id="yourModalID" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
...
</div>

And you are all set!

Georg Keferböck
  • 1,967
  • 26
  • 43