Last Updated: February 25, 2016
· devatotech

Start/Stop youtube video in Bootstrap modal

We're trying to show a youtube video in a modal. The iframe was preloaded on the page with the embed code. We were able to get it to auto start/stop based on the modal state:

Here's the modal:

<!-- Modal -->
<div class="modal fade bs-example-modal-lg" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <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 class="modal-body">
        <iframe width="640" height="360" src="https://www.youtube-nocookie.com/embed/<videoid>?rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

And the javascript to control youtube start/stop:

    var youtubeFunc ='';
    var outerDiv = document.getElementById("introVideo");
    var youtubeIframe = outerDiv.getElementsByTagName("iframe")[0].contentWindow;
    $('#introVideo').on('hidden.bs.modal', function (e) {
    youtubeFunc = 'pauseVideo';
    youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    $('#introVideo').on('shown.bs.modal', function (e) {
        youtubeFunc = 'playVideo';
      youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');

Notice the &enablejsapi=1 on the end of the URL. This is required or the stop/start functions will not work.

1 Response
Add your response


Do you have any idea why a would not play (using this example) on a smart phone? It works great on my desktop computer, but neither the iPhone or Android I use for testing. When I open with a smart phone, it very briefly shows the video "image" then the "video screen" turns black with a very "bitmap" like "key" shape in the top left - and I can not click it or play it. Thank you!

over 1 year ago ·