186

I'm trying to use the Modal feature from Bootstrap 3 to show my Youtube video. It works, but I can't click on any buttons in the Youtube video.

Any help on this?

Here's my code:

<div id="link">My video</div>

<div id="myModal" class="modal fade" 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">×</button>
            </div>
            <div class="modal-body">
                <iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
            </div>
        </div>
    </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.10.1.min.js"><\/script>')</script>
<script src="js/bootstrap.min.js"></script>
<script>
    $('#link').click(function () {
        var src = 'http://www.youtube.com/v/FSi2fJALDyQ&amp;autoplay=1';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    });

    $('#myModal button').click(function () {
        $('#myModal iframe').removeAttr('src');
    });
</script>
alex
  • 479,566
  • 201
  • 878
  • 984
NitroMedia
  • 2,011
  • 2
  • 13
  • 11

20 Answers20

122

I found this problem (or the problem I found and described at https://github.com/twbs/bootstrap/issues/10489) related to CSS3 transformation (translation) on the .modal.fade .modal-dialog class.

In bootstrap.css you will find the lines shown below:

.modal.fade .modal-dialog {
  -webkit-transform: translate(0, -25%);
      -ms-transform: translate(0, -25%);
          transform: translate(0, -25%);
  -webkit-transition: -webkit-transform 0.3s ease-out;
     -moz-transition: -moz-transform 0.3s ease-out;
       -o-transition: -o-transform 0.3s ease-out;
          transition: transform 0.3s ease-out;
}

.modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
      -ms-transform: translate(0, 0);
          transform: translate(0, 0);
}

Replacing these lines with the following will show the movie correctly (in my case):

.modal.fade .modal-dialog {
  -webkit-transition: -webkit-transform 0.3s ease-out;
     -moz-transition: -moz-transform 0.3s ease-out;
       -o-transition: -o-transform 0.3s ease-out;
          transition: transform 0.3s ease-out;
}

.modal.in .modal-dialog {

}
Trevor
  • 16,080
  • 9
  • 52
  • 83
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224
42

I put together this html/jQuery dynamic YouTube video modal script that auto plays the YouTube video when the trigger (link) is clicked, the trigger also contains the link to play. The script will find the native bootstrap modal call and open the shared modal template with the data from the trigger. See Below and let me know what you think. I would love to hear thoughts...

HTML MODAL TRIGGER:

 <a href="#" class="btn btn-default" data-toggle="modal" data-target="#videoModal" data-theVideo="http://www.youtube.com/embed/loFtozxZG0s" >VIDEO</a>

HTML MODAL VIDEO TEMPLATE:

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <div>
          <iframe width="100%" height="350" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

THE JQUERY FUNCTION:

//FUNCTION TO GET AND AUTO PLAY YOUTUBE VIDEO FROM DATATAG
function autoPlayYouTubeModal(){
  var trigger = $("body").find('[data-toggle="modal"]');
  trigger.click(function() {
    var theModal = $(this).data( "target" ),
    videoSRC = $(this).attr( "data-theVideo" ), 
    videoSRCauto = videoSRC+"?autoplay=1" ;
    $(theModal+' iframe').attr('src', videoSRCauto);
    $(theModal+' button.close').click(function () {
        $(theModal+' iframe').attr('src', videoSRC);
    });   
  });
}

THE FUNCTION CALL:

$(document).ready(function(){
  autoPlayYouTubeModal();
});

The FIDDLE: http://jsfiddle.net/jeremykenedy/h8daS/1/

jeremykenedy
  • 4,150
  • 1
  • 17
  • 25
  • 8
    This binds an event to the close button every time you open the modal, and also you should use the `hidden.bs.modal` event as a means of turning the video off, because the user can do other things to close the modal (e.g. click outside it). – Ian Clark Feb 13 '15 at 09:47
  • 1
    Autoplay is against the Youtube API terms. Just got an app rejected using webview in the Android app marketplace... – giorgio79 Sep 16 '16 at 20:48
  • Sounds like your app might have something else wrong with it. Here is YouTube's documentation. https://developers.google.com/youtube/player_parameters https://support.google.com/youtube/answer/6327615?co=GENIE.Platform%3DAndroid&hl=en – jeremykenedy Mar 26 '17 at 14:12
  • 2
    +1 It seems like Bootstrap itself is referring to your answer: https://getbootstrap.com/docs/4.3/components/modal/#embedding-youtube-videos – pimarc Dec 09 '19 at 21:28
  • sadly it doesn't work in BS5 :( – Devin Oct 13 '21 at 21:36
25

I have one tip for you!

I would use:

$('#myModal').on('hidden.bs.modal', function () {
    $('#myModal iframe').removeAttr('src');
})

instead of:

$('#myModal button').click(function () {
    $('#myModal iframe').removeAttr('src');
});

Because you can also close the modal without the button, so there for with this code it will remove the video every time the modal will hide.

Jeffrey Bouva
  • 409
  • 4
  • 12
  • At first glance it works, but what if you want to reopen this modal. You can't because you deleted `'src'` – kanlukasz May 04 '20 at 12:41
21

Found this in another thread, and it works great on desktop and mobile - which is something that didn't seem true with some of the other solutions. Add this script to the end of your page:

<!--Script stops video from playing when modal is closed-->
<script>
    $("#myModal").on('hidden.bs.modal', function (e) {
        $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
    });
</script>   
user664833
  • 18,397
  • 19
  • 91
  • 140
user2232930
  • 311
  • 2
  • 3
12

Here is another solution: Force HTML5 youtube video

Just add ?html5=1 to the source attribute on the iframe, like this:

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>
Community
  • 1
  • 1
  • 1
    The parameter html5=1 does not do anything (anymore) now. (Note it is not even listed at https://developers.google.com/youtube/player_parameters.) – Adarsh Madrecha Jul 16 '18 at 10:25
11

Bootstrap 5 (for readers reaching this from the Bootstrap docs)

This is an old Bootstrap 3 question, but I haven't found any answers that address controlling the playback.

As stated in the Bootstrap docs, the question is referenced to address the issue of "the modal requires additional JavaScript not in Bootstrap to automatically stop playback and more"

The YouTube video will work as expected in the Bootstrap modal as long as you're using an iframe instead of a video element to prevent CORS errors. However, iframe doesn't have video specific attributes like autoplay, loop, etc... which means the only playback controls are those embedded in the YT video. For example, you can't autostart the video when the modal opens (autostart=1 no longer works from the YT API)

The newer approach for controlling YouTube video playback is explained here. Here's how it would work specifically with video playback inside the Bootstrap 5 modal.

Modal markup

<div class="modal fade" id="dynamicVideoModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <div class="ratio ratio-21x9" id="player">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-dark" id="playBtn">Play</button>
                <button type="button" class="btn-dark" id="pauseBtn">Pause</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var player
function onYouTubeIframeAPIReady() {
    console.log('onYouTubeIframeAPIReady...')
    player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE', // YT video source
        playerVars: {
            'playsinline': 1
        },
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    })
}

function onPlayerReady(event) {
    event.target.playVideo() // autostart
}

function onPlayerStateChange(event) {
    // do other custom stuff here by watching the YT.PlayerState
}

function loadYouTubeVideo() {
    // 2. This code loads the IFrame Player API code asynchronously.
    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 myModalEl = document.getElementById('dynamicVideoModal')
myModalEl.addEventListener('show.bs.modal', function (event) {
    // dynamically create video when modal is opened
    loadYouTubeVideo()
})


// optional hooks for controls outside YT
var playBtn = document.getElementById('playBtn')
playBtn.addEventListener('click', function (event) {
    console.log('play')
    player.playVideo()
})

var pauseBtn = document.getElementById('pauseBtn')
pauseBtn.addEventListener('click', function (event) {
    console.log('pause')
    player.pauseVideo()
})

Bootstrap 5 YouTube Playback Demo


Update re: comment "problem is that video keeps playing when you close the modal window". This is out of scope from the OP question, but you'd simply hook into the modal hidden event and run .stop() on the appropriate instance of the YT player. For example:

dynamicVideoModal.addEventListener('hidden.bs.modal', event => {
    player.stopVideo()
})

Codeply (updated with stop on modal close)

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 1
    Thank you for the VanillaJS Bootstrap5 answer Zim. Couple of notes to add: (1). On the line: `player = new YT.Player('player', {` ... the 'player' in brackets corresponds to the div#player inside the modal body. (2). The loading of the YT iframe API scripts is asynchonous, so the `onPlayerReady(event)` seems to be the only way to trigger the video to play. In other words, even though `loadYouTubeVideo()` is within the `show.bs.modal` event, you would not be able to run `player.playVideo()` inside the `shown.bs.modal` event, because it probably won't be ready in time! – Bung Jun 23 '21 at 17:48
  • 1
    (3). The function `onYouTubeIframeAPIReady()` must be in global scope, I could not wrap it in my custom document ready handler for example. (4). With the responsive nature of Bootstrap, modals have various settings for their width at different breakpoints, so you will likely want to implement [this technique to make the video fluid width inside .modal-body](https://css-tricks.com/fluid-width-video/) – Bung Jun 23 '21 at 17:50
  • 1
    (5). If you want to use the modal as a template to launch different videos the user might click on, then inside #player I would recommend using the [ – Bung Jun 23 '21 at 17:51
  • Cool, thanks for the feedback. I will update the answer. – Carol Skelly Jun 23 '21 at 17:58
  • Cheers, not sure your answer needs any updates! I just meant I was adding some notes for others about things I ran into with a slightly different implementation :) – Bung Jun 24 '21 at 05:40
  • problem is that video keeps playing when you close the modal window – Robert Sinclair Mar 16 '23 at 16:03
  • 1
    works great! i see it's been added to the codeplay also. thank you! – Robert Sinclair Mar 16 '23 at 17:43
6

For Bootstrap 5

here I share what worked for me

Trigger button

<button data-bs-toggle="modal" data-tagVideo="https://www.youtube.com/embed/zcX7OJ-L8XQ" data-bs-target="#videoModal">Video</button>

Modal syntax

<div class="modal fade" id="videoModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="videoModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="ratio ratio-16x9">
          <iframe src="" allow="autoplay;" allowfullscreen></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

Function to get and autoplay Video from data

function autoPlayYouTubeModal() {
  var triggerOpen = $("body").find('[data-tagVideo]');
  triggerOpen.click(function() {
    var theModal = $(this).data("bs-target"),
      videoSRC = $(this).attr("data-tagVideo"),
      videoSRCauto = videoSRC + "?autoplay=1";
    $(theModal + ' iframe').attr('src', videoSRCauto);
    $(theModal + ' button.btn-close').click(function() {
      $(theModal + ' iframe').attr('src', videoSRC);
    });
  });
}

Call the function on document ready

<script>
  $(document).ready(function() {
    autoPlayYouTubeModal();
  });
</script>

And here the jsfiddle might have some Cors policy at first run so just refresh and click the button again

Ax_
  • 803
  • 8
  • 11
  • 2
    Thanks, @Alemens! How to stop video running after click outside with this b5 code? If to remove data-bs-backdrop="static" data-bs-keyboard="false". – Brgerg30879 May 26 '21 at 16:19
  • Hi @EvgenySudakov if you want to to stop video running after click outside see [Bootstrap 5 Options](https://getbootstrap.com/docs/5.0/components/offcanvas/#options) gives you possibility to set `data-bs-backdrop="true"` and `data-bs-keyboard="true"` so you also Closes the offcanvas when escape key is pressed – Ax_ Sep 20 '21 at 23:11
  • Thanks for your code, but the big advantage of BS5 is not having to stuff jQuery anymore :p – Boss COTIGA Dec 06 '22 at 17:46
5

Try this For Bootstrap 4

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container-fluid">
<h2>Embedding YouTube Videos</h2>
<p>Embedding YouTube videos in modals requires additional JavaScript/jQuery:</p>

<!-- Buttons -->
<div class="btn-group">
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/lQAUq_zs-XU">Launch Video 1</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/pvODsb_-mls">Launch Video 2</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/4m3dymGEN5E">Launch Video 3</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/uyw0VZsO3I0">Launch Video 4</button>
</div>

<!-- Modal -->
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-dark border-dark">
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body bg-dark p-0">
                <div class="embed-responsive embed-responsive-16by9">
                  <iframe class="embed-responsive-item" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

</div>

<script>
$(document).ready(function() {
    // Set iframe attributes when the show instance method is called
    $("#videoModal").on("show.bs.modal", function(event) {
        let button = $(event.relatedTarget); // Button that triggered the modal
        let url = button.data("video");      // Extract url from data-video attribute
        $(this).find("iframe").attr({
            src : url,
            allow : "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        });
    });

    // Remove iframe attributes when the modal has finished being hidden from the user
    $("#videoModal").on("hidden.bs.modal", function() {
        $("#videoModal iframe").removeAttr("src allow");
    });
});
</script>

</body>
</html>

visit (link broken): https://parrot-tutorial.com/run_code.php?snippet=bs4_modal_youtube

basZero
  • 4,129
  • 9
  • 51
  • 89
Vishal
  • 268
  • 4
  • 3
  • How to rotate or make fullscreen youtube video in mobil devices? Perhaps auto rotatation needed to make it landscape. – J C Dec 22 '21 at 07:53
4

I have solved it on wordpress template:

$videoLink ="http://www.youtube.com/watch?v=yRuVYkA8i1o;".   
<?php
    parse_str( parse_url( $videoLink, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube_ID = $my_array_of_vars['v'];    
?> 
<a class="video" data-toggle="modal" data-target="#myModal" rel="<?php echo $youtube_ID;?>">
    <img src="<?php bloginfo('template_url');?>/assets/img/play.png" />
</a>

<div class="modal fade video-lightbox" id="myModal" 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>
            <div class="modal-body"></div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script> 
    jQuery(document).ready(function ($) {
        var $midlayer = $('.modal-body');     
        $('#myModal').on('show.bs.modal', function (e) {
            var $video = $('a.video');
            var vid = $video.attr('rel');
            var iframe = '<iframe />';  
            var url = "//youtube.com/embed/"+vid+"?autoplay=1&autohide=1&modestbranding=1&rel=0&hd=1";
            var width_f = '100%';
            var height_f = 400;
            var frameborder = 0;
            jQuery(iframe, {
                name: 'videoframe',
                id: 'videoframe',
                src: url,
                width:  width_f,
                height: height_f,
                frameborder: 0,
                class: 'youtube-player',
                type: 'text/html',
                allowfullscreen: true
            }).appendTo($midlayer);   
        });

        $('#myModal').on('hide.bs.modal', function (e) {
            $('div.modal-body').html('');
        }); 
    });
</script>
mantal
  • 1,093
  • 1
  • 20
  • 38
Bijaya Kumar Oli
  • 2,007
  • 19
  • 15
4

If you don't want to edit the bootstrap CSS or all of the above doesn't help you at all (like in my case), there's an easy fix to get the video running in a modal on Firefox.

You just need to remove the "fade" class from the modal and as it opens the "in" class, too:

$('#myModal').on('shown.bs.modal', function () {
    $('#myModal').removeClass('in');
});
Sanzaru
  • 101
  • 2
  • 4
1

MMhh... Could you post your entire HTML doc and what browser/version your using?

I recreated your page and tested in 3 browsers (Chrome, FF, IE8). I was able to stop and start the awesome WDS4 trailer without any issues. Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet" media="screen">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="../../assets/js/html5shiv.js"></script>
      <script src="../../assets/js/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div id="link">My video</div>

    <div id="myModal" class="modal fade" 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">×</button>
                </div>

                <div class="modal-body">
                    <iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="jq.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap.min.js"></script>
    <script>
    $('#link').click(function () {
        var src = 'http://www.youtube.com/v/FSi2fJALDyQ&amp;autoplay=1';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    });

    $('#myModal button').click(function () {
        $('#myModal iframe').removeAttr('src');
    });
</script>
  </body>
</html>

You could try bringing the Z-Index of your modal player higher in the stack?

$('#myModal iframe').css("z-index","999");

biberman
  • 5,606
  • 4
  • 11
  • 35
TyMayn
  • 1,936
  • 2
  • 18
  • 23
  • I tried your code, but it didn't work. I can't click on any button in the video (pause, sound volume, quality, etc). Did you understand that i can't use any YOUTUBE buttons ? I'm looking at it in Firefox. - Which version of jquery are you using ? I'm using 1.10.1 - You were using Bootstrap 3 ? – NitroMedia Sep 05 '13 at 17:20
  • 1
    Continue my tests : DON'T WORK in Firefox WORK in Chrome WORK in Safari – NitroMedia Sep 05 '13 at 17:31
  • So I use your code, test it everywhere and it work everywhere except Firefox. On Mac, when I rollover a button, the color change but i can't click on them. On PC, screen stay black and the video is playing. It drives me crazy! I tried the to run firefox with the safe mode, empty my cache, nothing work. – NitroMedia Sep 05 '13 at 18:00
  • I found the same problem. For Firefox for ubuntu 23.0. But i got an error TypeError: Value not an object. http://s.ytimg.com/yts/jsbin/www-embed-player-vflwWlnaY.js (line 220). In chrome your code works. – Bass Jobsen Sep 05 '13 at 23:11
  • Mmhhh.. I've recreated it locally on my mac, and it tries to download the Video ID. Let me push it to my server and see if that a local bug. – TyMayn Sep 06 '13 at 20:23
1

Bootstrap does provide modal pop-up functionality out of the box.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<a class="btn btn-primary" data-toggle="modal" href="#modal-video"><i class="fa fa-play"></i> watch video</a>
<div class="modal fade" id="modal-video" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">close <i class="fa fa-times"></i></button>
      </div>
      <div class="modal-body">
        <iframe type="text/html" width="640" height="360" src="//www.youtube.com/embed/GShZUiyqEH0?rel=0?wmode=transparent&amp;fs=1&amp;rel=0&amp;enablejsapi=1&amp;version=3" frameborder="0" allowfullscreen=""></iframe>
        <p>Your video</p>
      </div>
    </div>
  </div>
</div>
coliff
  • 812
  • 8
  • 12
jagdish.narkar
  • 317
  • 1
  • 7
0
<a href="#" class="btn btn-default" id="btnforvideo" data-toggle="modal" data-target="#videoModal">VIDEO</a>

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <div>
                    <iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>
FahadAkram
  • 445
  • 1
  • 5
  • 25
0

using $('#introVideo').modal('show'); conflicts with bootstrap proper triggering. When you click on the link that opens the Modal it will close right after completing the fade animation. Just remove the $('#introVideo').modal('show'); (using bootstrap v3.3.2)

Here is my code:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>


<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" 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-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item allowfullscreen"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>


<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"> </script>

<script>
  //JS

$('#videoLink').click(function () {
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
    // $('#introVideo').modal('show'); <-- remove this line
    $('#introVideo iframe').attr('src', src);
});


$('#introVideo button.close').on('hidden.bs.modal', function () {
    $('#introVideo iframe').removeAttr('src');
})
</script>
0

user3084135's answer worked well as a base for me, but I also needed to incorporate:

  1. The "video" tag for locally-hosted video as well as the "iframe" tag for externally-hosted video
  2. Ensure that the source was removed however the modal was dismissed
  3. The solution worked in a Bootstrap responsive design
  4. All videos auto-play on modal open
  5. Multiple modals are possible

My finished solution looks like this:

MODAL TRIGGER BUTTON

<a href="#" class="portfolio-link" data-toggle="modal" data-frame="iframe" data-target="#portfolioModal1" data-theVideo="http://www.youtube.com/embed/xxxxxxxx">

The data-frame attribute can be either "iframe" or "video" to reflect the appropriate tag type: iframe for external vids, video for locally-hosted.

BOOTSTRAP RESPONSIVE VIDEO CONTAINERS

iFrame:

<div align="center" class="embed-responsive embed-responsive-16by9">
  <iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>
</div>

video:

<div align="center" class="embed-responsive embed-responsive-16by9">
    <video width="640" height="364" controls>
        <source src="" type="video/mp4">
        Your browser does not support the video tag.
    </video>                               
</div>

These both reside within the standard Bootstrap responsive modal divs.

JQUERY SCRIPT

<script>
 $(document).ready(function(){
    function autoPlayModal(){
      var trigger = $("body").find('[data-toggle="modal"]');
      trigger.click(function() {
        var theFrame = $(this).data( "frame" );
        var theModal = $(this).data( "target" );
        videoSRC = $(this).attr( "data-theVideo" ); 
        if (theFrame == "iframe") {
          videoSRCauto = videoSRC+"?autoplay=1" ;
        } else {
          videoSRCauto = videoSRC;
          $("[id*=portfolioModal] video").attr('autoplay','true');
        }
        $(theModal+' '+ theFrame).attr('src', videoSRCauto); 
        $("[id*=portfolioModal]").on('hidden.bs.modal', function () {
            $("[id*=portfolioModal] "+ theFrame).removeAttr('src');
        })
      });
    }

  autoPlayModal();
});
</script>

Since autoplay works differently with iframe and video tags, a conditional is used to deal with each. To allow multiple modals, a wildcard selector is used to identify them (portfolioModal1-6 in my case).

awvidmer
  • 155
  • 1
  • 14
0

I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
Fstarocka Burns
  • 163
  • 1
  • 5
0

Ok. I found a solution.

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
                    <p>Log in:</p>
                </div>

                <div class="modal-body">

                    <h4>Youtube stuff</h4>



             <iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>       
             </div>


                </div>

            </div>
        </div>
    </div>
Mwangi Thiga
  • 1,339
  • 18
  • 22
0

For Bootstrap 4, which handles videos, images and pages...

http://jsfiddle.net/c4j5pzua/

$('a[data-modal]').on('click',function(){
 var $page = $(this).data('page');
 var $image = $(this).data('image');
 var $video = $(this).data('video');
 var $title = $(this).data('title');
 var $size = $(this).data('size');
 $('#quickview .modal-title').text($title);
 if ($size) { $('#quickview .modal-dialog').addClass('modal-'+$size); }
 if ($image) {
  $('#quickview .modal-body').html('<div class="text-center"><img class="img-fluid" src="'+$image+'" alt="'+$title+'"></div>');
 } else if ($video) {
  $('#quickview .modal-body').html('<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/'+$video+'?autoplay=1" allowfullscreen></iframe></div>');
 }
 if ($page) {
  $('#quickview .modal-body').load($page,function(){
   $('#quickview').modal({show:true});
  });
 } else {
  $('#quickview').modal({show:true});
 }
 $('#quickview').on('hidden.bs.modal', function(){
  $('#quickview .modal-title').text('');
  $('#quickview .modal-body').html('');
  if ($size) { $('#quickview .modal-dialog').removeClass('modal-'+$size); }
 });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

<div class="container my-4">

<h3 class="mb-4">Bootstrap 4 Modal YouTube Videos, Images & Pages</h3>

<a href="javascript:;" class="btn btn-primary" data-modal data-video="zpOULjyy-n8" data-title="Video Title" data-size="xl">Video</a>

<a href="javascript:;" class="btn btn-primary" data-modal data-image="https://v4-alpha.getbootstrap.com/assets/brand/bootstrap-social-logo.png" data-title="Image Title" data-size="">Image</a>

<a href="javascript:;" class="btn btn-primary" data-modal data-page="https://getbootstrap.com" data-title="Page Title" data-size="lg">Page *</a>

<p class="mt-4">* Clicking this will break it, but it'll work using a local page!</p>

</div>

<div class="modal fade" id="quickview" tabindex="-1" role="dialog" aria-labelledby="quickview" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
xcartmods
  • 1
  • 1
0

Using LATEST Bootstrap 4.5+

  • Use the same modal repeatedly by passing different Youtube URL's from the HTML Page
  • With a great Play button icon and Autoplay enabled
  • Just COPY the code and you are all SET!!!
  • View solution in Codepen

    // javascript using jQuery - can embed in the script tag
$(".video-link").click(function () {
  var theModal = $(this).data("target");
  videoSRC = $(this).attr("data-video");
  videoSRCauto = videoSRC + "?modestbranding=1&rel=0&showinfo=0&html5=1&autoplay=1";
  $(theModal + ' iframe').attr('src', videoSRCauto);
  $(theModal + ' button.close').click(function () {
    $(theModal + ' iframe').attr('src', videoSRC);
  });
});
#video-section .modal-content {
  min-width: 600px;
}

#video-section .modal-content iframe {
  width: 560px;
  height: 315px;
}
<!-- HTML with Bootstrap 4.5 and Fontawesome -->
<html>
   <head>
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css"
         integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
   </head>

   <body>
      <section id="video-section" class="py-5 text-center text-white">
         <div class="container h-100 d-flex justify-content-center">
            <div class="row align-self-center">
               <div class="col">
                  <div class="card bg-dark border-0 mb-2 text-white">
                     <div class="card-body">
                        <a href="#" class="btn btn-primary bg-dark stretched-link video-link" data-video="https://www.youtube.com/embed/HnwsG9a5riA" data-toggle="modal" data-target="#video-modal">
                        <i class="fas fa-play fa-3x"></i>
                        </a>
                        <h1 class="card-title">Play Video</h1>
                     </div>
                  </div>
               </div>
            </div>
         </div>

         <!-- Video Modal -->
         <div class="modal fade" id="video-modal" tabindex="-1" role="dialog">
            <div class="modal-dialog h-100 d-flex align-items-center">
               <div class="modal-content">
                  <div class="modal-body">
                     <button type="button" class="close" data-dismiss="modal">
                     <span>&times;</span>
                     </button>
                     <iframe frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                  </div>
               </div>
            </div>
         </div>
      </section>

      <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

   </body>
</html>


  [1]: https://codepen.io/richierich25/pen/yLOOYBL
RICHARD ABRAHAM
  • 2,218
  • 20
  • 26
-3

$('#videoLink').click(function () {
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
    // $('#introVideo').modal('show'); <-- remove this line
    $('#introVideo iframe').attr('src', src);
});

$('#introVideo button.close').on('hidden.bs.modal', function () {
    $('#introVideo iframe').removeAttr('src');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>

<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" 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-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item allowfullscreen"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>
grg
  • 5,023
  • 3
  • 34
  • 50
Kondal
  • 1
  • 1