Youtube Video Still Playing When Bootstrap Modal Closes

两盒软妹~` 提交于 2020-01-20 16:52:26

问题


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>

`


回答1:


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>



回答2:


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"));
});



回答3:


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/




回答4:


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', '');
});



回答5:


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);
});



回答6:


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.




回答7:


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
    }
}



回答8:


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...




回答9:


<!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.




回答10:


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>



回答11:


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()
    });



回答12:


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.



来源:https://stackoverflow.com/questions/22613303/youtube-video-still-playing-when-bootstrap-modal-closes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!