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&autoplay=1'; $('#myModal').modal('show'); $('#myModal iframe').attr('src', src); }); $('#myModal button').click(function () { $('#myModal iframe').removeAttr('src'); });</script>
20 Answers20
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 {}
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">×</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:
5 Comments
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).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.
1 Comment
'src'
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>
1 Comment
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()})
7 Comments
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!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 implementthis technique to make the video fluid width inside .modal-bodyshow.bs.modal
before you callloadYouTubeVideo()
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>
1 Comment
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
3 Comments
data-bs-backdrop="true"
anddata-bs-keyboard="true"
so you also Closes the offcanvas when escape key is pressedTry 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">×</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
1 Comment
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">×</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>
1 Comment
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');});
Comments
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&fs=1&rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen=""></iframe> <p>Your video</p> </div> </div> </div></div>
Comments
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>×</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
1 Comment
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&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");
5 Comments
user3084135's answer worked well as a base for me, but I also needed to incorporate:
- The "video" tag for locally-hosted video as well as the "iframe" tag for externally-hosted video
- Ensure that the source was removed however the modal was dismissed
- The solution worked in a Bootstrap responsive design
- All videos auto-play on modal open
- 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).
Comments
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">
Comments
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">×</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>
Comments
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">×</button> <div> <iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe> </div> </div> </div> </div></div>
2 Comments
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; }); });});
Comments
For Bootstrap 4, which handles videos, images and pages...
$('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">×</span></button></div><div></div></div></div></div>
Comments
$('#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">×</span></button> </div> <div> <div> <iframe></iframe> </div> </div> </div> </div></div>
1 Comment
Explore related questions
See similar questions with these tags.