189

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

How can I fix it?

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>
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
askedSep 4, 2013 at 19:45
NitroMedia's user avatar
0

20 Answers20

123

I found this problem (or the problem I found and described athttps://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 {}
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredSep 6, 2013 at 10:21
Bass Jobsen's user avatar
Sign up to request clarification or add additional context in comments.

2 Comments

This should not be the accepted answer. One must not edit source css files.
they can be overridden (in a new file), by just setting every field to unset.transform: unset;
42

I put together this HTML/jQuery dynamic YouTube video modal script that auto plays the YouTube video when the trigger (link) is clicked, and 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. Seebelow.

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>

HTMLmodal 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 datatagfunction 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 JSFiddle:

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

Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredMay 13, 2014 at 11:03
jeremykenedy's user avatar

5 Comments

This binds an event to the close button every time you open the modal, and also you should use thehidden.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).
Autoplay is against the Youtube API terms. Just got an app rejected using webview in the Android app marketplace...
Sounds like your app might have something else wrong with it. Here is YouTube's documentation.developers.google.com/youtube/player_parameterssupport.google.com/youtube/answer/…
+1 It seems like Bootstrap itself is referring to your answer:getbootstrap.com/docs/4.3/components/modal/…
sadly it doesn't work in BS5 :(
26

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.

answeredOct 2, 2013 at 13:44
Jeffrey Bouva's user avatar

1 Comment

At first glance it works, but what if you want to reopen this modal. You can't because you deleted'src'
22

I 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>
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredSep 16, 2014 at 13:26
user2232930's user avatar

1 Comment

This code works for me. Simple and efficient! Thank you!
14

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

This is an old Bootstrap 3 question, but I haven't foundany 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 aniframe instead of avideo element to prevent CORS errors.However,iframe doesn't have video specific attributes likeautoplay, loop, etc... which means the only playback controls are those embedded in the YT video. For example, you can'tautostart the video when the modal opens (autostart=1 no longer works from the YT API)

The newer approach forcontrolling 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 playerfunction 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 YTvar 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 modalhidden 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)

answeredJun 11, 2021 at 14:24
Carol Skelly's user avatar

7 Comments

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 theonPlayerReady(event) seems to be the only way to trigger the video to play. In other words, even thoughloadYouTubeVideo() is within theshow.bs.modal event, you would not be able to runplayer.playVideo() inside theshown.bs.modal event, because it probably won't be ready in time!
(3). The functiononYouTubeIframeAPIReady() 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 implementthis technique to make the video fluid width inside .modal-body
(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<iframe> technique here. Then you can generate a new src string and change the iframe source onshow.bs.modal before you callloadYouTubeVideo()
Cool, thanks for the feedback. I will update the answer.
works great! i see it's been added to the codeplay also. thank you!
|
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>
answeredOct 15, 2013 at 18:46
Chris Scheler's user avatar

1 Comment

The parameter html5=1 does not do anything (anymore) now. (Note it is not even listed atdevelopers.google.com/youtube/player_parameters.)
8

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

answeredFeb 18, 2021 at 11:17
Ax_'s user avatar

3 Comments

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".
Hi @EvgenySudakov if you want to to stop video running after click outside seeBootstrap 5 Options gives you possibility to setdata-bs-backdrop="true" anddata-bs-keyboard="true" so you also Closes the offcanvas when escape key is pressed
Thanks for your code, but the big advantage of BS5 is not having to stuff jQuery anymore :p
4

Try thisFor 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's user avatar
basZero
4,2949 gold badges55 silver badges89 bronze badges
answeredJun 12, 2019 at 17:22
Vishal's user avatar

1 Comment

How to rotate or make fullscreen youtube video in mobil devices? Perhaps auto rotatation needed to make it landscape.
4

I have solved it in aWordPress 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>
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredJan 27, 2014 at 7:41
Bijaya Kumar Oli's user avatar

1 Comment

In what way? What is the gist? What is the idea? How does it work?
4

If you don't want to edit the Bootstrap CSS or all of the previous answers 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');});
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredMar 18, 2014 at 19:59
Sanzaru's user avatar

Comments

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 data-toggle="modal" href="#modal-video"><i></i> watch video</a><div>  <div>    <div>      <div>        <button type="button" data-dismiss="modal" aria-hidden="true">close <i></i></button>      </div>      <div>        <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's user avatar
coliff
1,06512 silver badges13 bronze badges
answeredMar 9, 2017 at 21:34
jagdish.narkar's user avatar

Comments

1

Using LATESTBootstrap 4.5+

  • Use the same modal repeatedly by passing different Youtube URL's from the HTML Page
  • With a greatPlay button icon andAutoplay enabled
  • JustCOPY the code and you are allSET!!!
  • View solution inCodepen

    // 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>         <div>            <div>               <div>                  <div>                     <div>                        <a href="#" data-video="https://www.youtube.com/embed/HnwsG9a5riA" data-toggle="modal" data-target="#video-modal">                        <i></i>                        </a>                        <h1>Play Video</h1>                     </div>                  </div>               </div>            </div>         </div>         <!-- Video Modal -->         <div tabindex="-1" role="dialog">            <div>               <div>                  <div>                     <button type="button" 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/[email protected]/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
answeredAug 14, 2020 at 15:45
RICHARD ABRAHAM's user avatar

1 Comment

This code work for vimeo videos? Or needs some changes
1

I recreated your page and tested in three browsers (Chrome, Firefox, andInternet Explorer 8). 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-order of your modal player higher in the stack:

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

Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredSep 4, 2013 at 20:20
TyMayn's user avatar

5 Comments

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 ?
Continue my tests : DON'T WORK in Firefox WORK in Chrome WORK in Safari
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.
I found the same problem. For Firefox for ubuntu 23.0. But i got an error TypeError: Value not an object.s.ytimg.com/yts/jsbin/www-embed-player-vflwWlnaY.js (line 220). In chrome your code works.
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.
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="#" 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">  <iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe></div>

video:

<div align="center">    <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).

answeredJun 5, 2015 at 20:58
awvidmer's user avatar

Comments

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">
answeredJun 26, 2016 at 10:41
Fstarocka Burns's user avatar

Comments

0

Using$('#introVideo').modal('show'); conflicts with Bootstrap's 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 href="#0" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a><!-- Intro video --><div tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">  <div>    <div>      <div>        <button type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>      </div>      <div>        <div>            <iframe></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>

Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredMar 19, 2015 at 10:32
Imadeddine Bouziani's user avatar

Comments

0

Use:

<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>
Peter Mortensen's user avatar
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answeredJan 22, 2015 at 8:23
FahadAkram's user avatar

2 Comments

That is a code dump. What is the gist?
OK, the OP hasleft the building:"Last seen more than 3 years ago "
0

This simple JavaScript snippet can be used to clear the iframe's input when a modal is closed. It works with Vimeo, YouTube and any other media-playing iframes automatically with no further configuration.

document.addEventListener("DOMContentLoaded", function () {  document.body.addEventListener("hidden.bs.modal", function (event) {    const iframes = event.target.querySelectorAll("iframe");    iframes.forEach(function (iframe) {      iframe.src = iframe.src;    });  });});
answeredMay 26 at 8:29
coliff's user avatar

Comments

-1

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><img src="'+$image+'" alt="'+$title+'"></div>');} else if ($video) {$('#quickview .modal-body').html('<div><iframe 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><h3>Bootstrap 4 Modal YouTube Videos, Images & Pages</h3><a href="#" data-modal data-video="zpOULjyy-n8" data-title="Video Title" data-size="xl">Video</a><a href="#" 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="#" data-modal data-page="https://getbootstrap.com" data-title="Page Title" data-size="lg">Page *</a><p>* Clicking this will break it, but it'll work using a local page!</p></div><div tabindex="-1" role="dialog" aria-labelledby="quickview" aria-hidden="true"><div role="document"><div><div><h5>Title</h5><button type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div><div></div></div></div></div>

answeredMar 22, 2019 at 20:21
xcartmods's user avatar

Comments

-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 href="#0" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a><!-- Intro video --><div tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">  <div>    <div>      <div>        <button type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>      </div>      <div>        <div>            <iframe></iframe>        </div>      </div>    </div>  </div></div>

grg's user avatar
grg
6,0644 gold badges40 silver badges57 bronze badges
answeredJul 4, 2016 at 11:44
Kondal's user avatar

1 Comment

Example does not run

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.