title: Bootstrap Modals & Youtube: Autoplay and Stop on Close
body: <p>I need to be able to autoplay a youtube video when a Twitter Bootstrap modal is opened and subsequently stop that video on close.</p>
  
  <p>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.</p>
  
  <pre><code>$('#vidThumbnail-1').click(function () {
          var src = 'http://www.youtube.com/embed/8bKmrhI-YT8?&amp;amp;autoplay=1';
          $('#vid1').modal('show');
          $('#vid1 iframe').attr('src', src);
  
        //Fit Vids Implamented Below for Mobile Compatibility
          $("#vid1Thumbnail-1 iframe").wrap("&lt;div class='flex-video'/&gt;");
          $(".flex-video").fitVids();
      });
  $('#vid1 button').click(function () {
          $('#vid1 iframe').removeAttr('src');
      });
  </code></pre>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div id="vidThumbnail-1"&gt;&lt;img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg" /&gt;&lt;/div&gt;
  
  &lt;div id="vid1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt;
      &lt;div class="modal-body"&gt;
          &lt;iframe src="http://www.youtube.com/embed/8bKmrhI-YT8" width="640" height="360" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;   
          &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>&lt;a href="#vid1" role="button" data-toggle="modal"&gt;
  &lt;img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg"&gt;&lt;/a&gt;
  </code></pre>
  
  <p>Then:</p>
  
  <ol>
  <li>Read the existing src attribute of the iframe in the target modal (set that to a variable?)</li>
  <li>Append the existing src attribute with "&amp;autoplay=1" to initiate the video.</li>
  <li>Replace the src attribute with the original upon closing the modal (via the button specifically like it is above is fine).</li>
  </ol>
  
  <p>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!</p>