Bootstrap Modals & Youtube: Autoplay and Stop on C

2019-04-08 17:47发布

问题:

I need to be able to autoplay a youtube video when a Twitter Bootstrap modal is opened and subsequently stop that video on close.

I know this question has been asked before, but the answers I can find would lead to a LOT of javascript code for a page that contains MANY videos and I am trying to cut down on the bloat. So far I have the following working for individual videos, but the issue is that each modal and each video must have this javascript code repeated with the proper variables.

$('#vidThumbnail-1').click(function () {
        var src = 'http://www.youtube.com/embed/8bKmrhI-YT8?&autoplay=1';
        $('#vid1').modal('show');
        $('#vid1 iframe').attr('src', src);

      //Fit Vids Implamented Below for Mobile Compatibility
        $("#vid1Thumbnail-1 iframe").wrap("<div class='flex-video'/>");
        $(".flex-video").fitVids();
    });
$('#vid1 button').click(function () {
        $('#vid1 iframe').removeAttr('src');
    });

HTML:

<div id="vidThumbnail-1"><img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg" /></div>

<div id="vid1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
        <iframe src="http://www.youtube.com/embed/8bKmrhI-YT8" width="640" height="360" frameborder="0" allowfullscreen></iframe>   
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    </div>
  </div>

This gets bloated when you have 20 videos and 20 modals! Is there a way to utilize the Data Attributes method of initiating a modal built-into bootstrap rather than call it individually, while still modifying the iframe src within only the target modal? The link to open the modal would then be:

<a href="#vid1" role="button" data-toggle="modal">
<img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg"></a>

Then:

  1. Read the existing src attribute of the iframe in the target modal (set that to a variable?)
  2. Append the existing src attribute with "&autoplay=1" to initiate the video.
  3. Replace the src attribute with the original upon closing the modal (via the button specifically like it is above is fine).

This way I would not need to write script for each individual modal, saving a lot of time AND bloated JS. However, I have no idea where to start modifying the bootstrap.js to accomplish this and I'm not experienced in JS (or any) programming. Thanks for any help you can give me!

回答1:

My solution:

  • do not add &amp;autoplay=1 to the iframe src manually

then add this script:

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+"&amp;autoplay=1");
});

$("#myModal").on('hidden.bs.modal', function (e) { // on closing the modal
  // stop the video
  $("#myModal iframe").attr("src", null);
});


回答2:

                    <div class="close-button">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                    </div>

   $('.close').on('click', function (e) {
        $("#myModal iframe").attr("src", null);
    });


回答3:

Hello @Benjamin Morrison Hope you got the solution already, I am answering this for other user who are still searching for same solution

$(document).ready(function() {
  $('.modalclick').on('click', function(e) {
    e.preventDefault();
    var src = $(this).attr('href');
    $('#myModal').modal('show');
    $('#myModal iframe').attr('src', src);
  });
  //auto close or pause on model hide
  $("#myModal").on('hidden.bs.modal', function(e) {
    $("#myModal iframe").attr("src", '');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
        <iframe src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

      </div>
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">SKIP >></button>

      </div>
    </div>
  </div>
</div>
<a class="modalclick" href="https://www.youtube-nocookie.com/embed/3j4nia24Oms?rel=0&showinfo=0&autoplay=1">click me</a><br>
<a class="modalclick" href="https://www.youtube.com/embed/ycK617mKlvA?rel=0&showinfo=0&autoplay=1">click me 1</a><br>
<a class="modalclick" href="https://www.youtube.com/embed/z329gFDUJis?rel=0&showinfo=0&autoplay=1">click me 2</a>

Just Add Youtube Embed url on href tag of clickable link, you can make as many as link you link. @Benjamin in your case keep image inside anchor tag so that Image is clickable.



回答4:

Here is a JS Fiddle.

I've added a bit of progressive enhancement so were the JS to fail you would be taken to the YouTube video in this case.

The link requires a data-video-embed and a target to where we are going to be adding the video every thing else should just work. The event in the example is for Bootstrap 3 modal if you are using 2.X it will just be 'hide'.

$('[data-provider="modal-video"]')
   .on('click', function (evt) {
      evt.preventDefault();
      var $target = $(evt.currentTarget),
          videoSrc = $target.data('video-embed'),
          $modal = $($target.data('target'));

      $modal
        .find('iframe').attr('src', videoSrc)
        .end()
        .on('hide.bs.modal', function () {
            $(this)
                .off('hide.bs.modal')
                .find('iframe').attr('src', '');
        })
        .modal('show');
});


回答5:

I couldn't find a dynamic way to handle this issue, so I created a dynamic way to handle this for a site that we are working on.

Here are the links:

<li><a href="#" data-toggle="modal" data-target="#video1">Video: video 1</a></li>
<li><a href="#" data-toggle="modal" data-target="#video2">Video: video 2</a></li>

Here are the modals:

<div id="video1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/vidpath" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div id="video2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/vidpath2" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>

Here is the script:

// autoplay video functionality
$( "[data-target^='#video']" ).click(function() { 
    // get the ID of the clicked video
    var dataTarget = $(this).attr("data-target");
    dataTarget = dataTarget.substring(1,7); 
    var vidId = '#'+dataTarget; 

    // get the vid src
    var vidSrc = $(vidId+ " iframe").attr('src');

    // create the autoplay
    var vidSrcAuto = vidSrc+'?autoplay=1'; 

    // get the iframe element
    var iframeEl = $(vidId+ " iframe"); 


    $(vidId).on('show.bs.modal', function () {  
        $(iframeEl).attr("src", vidSrcAuto);
    });

    $(vidId).on('hidden.bs.modal', function (e) {  
        $(iframeEl).attr("src", vidSrc);  
    });   

});