Twitter Bootstrap Modal Event Not Fired When Modal is Shown - javascript

According to the docs:
http://getbootstrap.com/javascript/#modals
It should fire the methods "show.bs.dropdown" and "shown.bs.dropdown". But it doesn't:
http://jsfiddle.net/mQunq/3/
HTML:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world</div>
</div>
</div>
jQuery:
// show.bs.modal doesn't work either
$('#myModal')
.modal('show')
.on('show.bs.modal', function() {
alert('shown baby!');
});

Youe need first register event then trigger it
$('#myModal')
.on('show.bs.modal', function() {
alert('shown baby!');
}).modal('show');
jsfiddle

When it happens
Event shown.bs.modal is not fired when modal has also class "fade". Whereas show.bs.modal always works.
See https://github.com/twbs/bootstrap/issues/11793
HTML:
<div class="modal fade" id="first" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world from first modal</div>
</div>
</div>
<div class="modal" id="second" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world from second modal</div>
</div>
</div>
jQuery:
$('.modal').on('shown.bs.modal', function() {
//fired only in second modal
console.info('shown.bs.modal');
});
$('.modal').on('show.bs.modal', function() {
//fired always
console.info('show.bs.modal');
});
Solution
For bootstrap v3.3.6 replace line 1010 with:
that.$element // wait for modal to slide in
What is the problem
Look at lines 1006-1015:
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
Without transition (no fade class) the event e is triggered right away (on that.$element).
With transition, I'm not sure why exactly, but somehow the bsTransationEnd event from function emulateTransitionEnd is not handled by that.$dialog.one(). But with that.$element, everything seem to work.

Similar thing happened to me and I have solved using setTimeout.
Bootstrap is using the following timeout to complete showing:
c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,
So using more than 300 must work and for me 200 is working:
$('#myModal').on('show.bs.modal', function (e) {
setTimeout(function(){
//Do something if necessary
}, 300);
})

you forgot the "n" on shown
$(document).ready(function(){
$('#myModal')
.modal('show')
.on('shown.bs.modal', function() {
alert('shown baby!');
});
});

Use document instead of your custom selector. Both shown.bs.modal and show.bs.modal work just fine
$(document).on('shown.bs.modal', '.modal', function() {
alert();
});

In case someone stumbles upon this problem, make sure you hook the on hidden / shown event before firing the toggle of the modal. That is, declare this:
$("#selector").on("hidden.bs.modal", function () {
// do the right thing
});
Before calling the toggle of the modal, e.g.:
("#selector").modal("toggle");
I know this is basic, but in a convoluted code it happens.

I found a solution that works with .fade transitions:
$(document).on($.support.transition.end, '.modal.fade.in', function(e) {
var $target = $(e.target);
if ($(e.target).is(".modal-dialog")) {
console.log("Modal Shown")
}
});
$(document).on($.support.transition.end, '.modal.fade', function(e) {
var $target = $(e.target);
if (!$target.is(".modal.fade.in") && !$target.is(".modal-dialog")) {
console.log("Modal Hidden")
}
});

If your modal is dynamically created, select the closest static parent element and add your modal as a parameter for bootstrap modal events to work:
/* body is static, .modal is not */
$("body").on('shown.bs.modal', '.modal', function() {
alert('shown');
});
$("body").on('hidden.bs.modal', '.modal', function() {
alert('hidden');
});
$("body").on('show.bs.modal', '.modal', function() {
alert('show');
});
$("body").on('hide.bs.modal', '.modal', function() {
alert('hide');
});

Related

How to popup javascript modal with code instead of button click

I have the following modal:
<div class="modal fade" id="m_modal_1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
I have the following button that pops up the modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#m_modal_1"> Launch Modal</button>
Instead of initiating from the button, how do I popup from code? I was thinking something like this:
if(status == 1){
modal("show");
}
Assuming that you're using Bootstrap (based on the classes).
You can use the following:
$('#m_modal_1').modal('show')
You need to add eventlistener to any element, so once the event is triggered you change classes of the modal element or style.
Assuming you have some element (ie button with classname btn and modal with classname modal)
document.querySelector('.btn').addEventListener('click', () => {
document.querySelector('.modal').classList.toggle('hidden');
}
And your css can be like this
.hidden {
display: none;
// or
opacity: 0;
}
I think you are using bootstrap.
so in your case
if(status == 1){
$("#m_modal_1").modal("show");
}
"show" is a option of modal function.
See more option and usage here
https://getbootstrap.com/docs/4.0/components/modal/#options
Basically it depends on when you want to popup your modal.suppose you want to popup on page
ready then,
$(document).ready(function(e){
$(#modal_id).show();
});

How to Fade In a notification by clicking a text field

Hi guys I need help (again). I wanted to learn how to make the notification or alert box fade-in and fade-out after clicking a editable textbox.
This is the code for the alert box:
<div class="alert alert-warning fade in">
×
Alert: Please don't do this.
</div>
and this is the script for onClick:
function clicks() {
document.getElementById("notif").innerHTML = "Hello World";
}
</script>
I was thinking I will put the div alert box inside a condition or just a script with onClick function
Working example on CodePen: http://codepen.io/oculusriff/pen/aBoKvE
HTML
<div id="alert" class="alert alert-warning fade">
×
Alert: Please don't do this.
</div>
<textarea id="txt"></textarea>
JS
var textarea = document.getElementById('txt');
var alert = document.getElementById('alert');
txt.addEventListener('focus', function() {
alert.classList.add('in');
setTimeout(function() {
alert.classList.remove('in');
}, 2000);
});
txt.addEventListener('blur',function (){
alert.classList.remove('in')
});
I would recommend using CSS approach to the animation. i.e. on click add/remove a class and let css handle the animation.
However if you want to use a JavaScript solution , here is one that does not change your code much
var myclickHandler = function() {
// first show the alert
$('.alert').show().fadeTo(500, 1);
// Now set a timeout to hide it
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).hide();
});
}, 3000);
}
// start with the alert hidden
$('.alert').hide();
$('#myTextBox').on('click', myclickHandler)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert alert-warning fade in">
× Alert: Please don't do this.
</div>
<input id="myTextBox" type="text" value="Click here">

if same class, fadeIn / fadout

I have a setup here in jsFiddle: http://jsfiddle.net/2PmnQ/
I'm trying to make a function that will check if the modal has the same class as the button so the button will bring up the modal with the same class. I'm obviously trying to do this dynamically all within one function rather than doing a if statement for every class.
var p = $(".popUp");
var position = p.position();
var tagLength = $("p a").width();
$( ".modal" ).css({left: (position.left + tagLength + 10) + "px", top: position.top + "px"});
$( ".popUp").hover(
function() {
$( ".modal" ).stop().fadeIn();
}, function() {
$( ".modal" ).stop().fadeOut();
}
);
I would use a custom data attribute instead of a class to save the target class:
<p class="popUp" data-modal="one"><a>popUp one here</a></p>
<p class="popUp" data-modal="two"><a>popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
That way you don't have to filter the target out of the trigger element classes and only need this in your hover function:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal')).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
http://jsfiddle.net/2PmnQ/1/
V2 using jQuery UI position() plugin:
<!-- i switched the popup classes to the `a` here so it works in the fiddle -->
<p><a class="popUp" data-modal="one">popUp one here</a></p>
<p><a class="popUp" data-modal="two">popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
JS:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal'))
// reset positions otherwise it doesn't work correctly after the first time. don't know why :(
// looks like this problem: http://forum.jquery.com/topic/position-keeps-adding-original-left-and-top-to-current-values-in-ie-8
.css({'left':0,'top':0})
// position modal 10px to the right of the popup link
.position({'my':'left+10 center',
'at' : 'right center',
'of' : $(this)
}
).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
http://jsfiddle.net/2PmnQ/10/
(Be sure to include the jQuery UI with at least the position plugin: http://jqueryui.com/download/#!version=1.11.0&components=0001000000000000000000000000000000000. Yeah maybe it's a bit overkill for this but it's really convenient)

Bootstrap Alert Auto Close

My need is to call alert when I click on Add to Wishlist button and should disappear the alert in 2 secs. This is how I tried, but the alert is disappearing instantly as soon as it is appearing. Not sure, where the bug is.. Can anyone help me out?
JS Script
$(document).ready (function(){
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
window.setTimeout(function () {
$("#success-alert").alert('close');
}, 2000);
});
});
HTML Code:
<div class="product-options">
<a id="myWish" href="" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
Alert Box:
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success!</strong>
Product have added to your wishlist.
</div>
For a smooth slide-up:-
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").slideUp(500);
});
$(document).ready(function() {
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").fadeTo(2000, 500).slideUp(500, function() {
$("#success-alert").slideUp(500);
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="product-options">
<a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong> Product have added to your wishlist.
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Using a fadeTo() that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()
$(".alert").delay(4000).slideUp(200, function() {
$(this).alert('close');
});
Why all the other answers use slideUp is just beyond me. As I'm using the fade and in classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.
Besides the slideUp method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:
$(document).ready(function() {
// show the alert
setTimeout(function() {
$(".alert").alert('close');
}, 2000);
});
I found this to be a better solution
$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-dismissible").alert('close');
});
one more solution for this
Automatically close or fade away the bootstrap alert message after 5 seconds:
This is the HTML code used to display the message:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="alert alert-danger">
This is an example message...
</div>
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function(){
$(this).remove();
});
}, 5000);
});
</script>
It's not limited to showing the message through JS, the message could already be displayed when the page loads.
I know this thread is old, but I just thought I would add my script for Bootstrap 5, incase anyone else needs it
<script>
setTimeout(function() {
bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
}, 3000)
</script>
Html:
<div class="alert alert-info alert-dismissible fade show js-alert" role="alert">
Javascript:
if (document.querySelector('.js-alert')) {
document.querySelectorAll('.js-alert').forEach(function($el) {
setTimeout(() => {
$el.classList.remove('show');
}, 2000);
});
}
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
Where fadeTo parameters are fadeTo(speed, opacity)
This is a good approach to show animation in and out using jQuery
$(document).ready(function() {
// show the alert
$(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
$(this).remove();
});
});
Tiggers automatically and manually when needed
$(function () {
TriggerAlertClose();
});
function TriggerAlertClose() {
window.setTimeout(function () {
$(".alert").fadeTo(1000, 0).slideUp(1000, function () {
$(this).remove();
});
}, 5000);
}
C# Controller:
var result = await _roleManager.CreateAsync(identityRole);
if (result.Succeeded == true)
TempData["roleCreateAlert"] = "Added record successfully";
Razor Page:
#if (TempData["roleCreateAlert"] != null)
{
<div class="alert alert-success">
×
<p>#TempData["roleCreateAlert"]</p>
</div>
}
Any Alert Auto Close:
<script type="text/javascript">
$(".alert").delay(5000).slideUp(200, function () {
$(this).alert('close');
});
</script>
This worked perfectly even though you clicked the button multiple times.
Here I created an onClick function to trigger the closeAlert function.
function closeAlert(){
const alert = document.getElementById('myalert')
alert.style.display = "block"
setTimeout(function(){
alert.style.display = "none"
}, 3000);
}

Twitter Bootstrap Modal stop Youtube video

I'm very new to javascript and trying to use Twitter bootstrap to get a good looking website up and running quickly. I know this has something to do with jquery, but I'm not sure how to stop my video when I push the close button or the close icon.
Can someone explain how I can get my video to stop playing because even when I close the window, I can still hear it in the background.
<!-- Button to trigger modal -->
<img src="img/play.png">
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role=labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria>×</button>
<h3 id="myModalLabel">I am the header</h3>
</div>
<div class="modal-body">
<p><iframe width="100%" height="315" src="http:com/embed/662KGcqjT5Q" frameborder="0" allowfullscreen></iframe></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
I know I'm 2+ years late, but since then, a couple of things have changed, with B3 the new way to perform this out of the box is this:
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
Have fun with Bootstrap!
There is a nice proper way of doing this - see the comments in the approved answer to this post.
Couldn't get that working first time round myself though, and was in a rush, so I did a rather horrible hacky bit of code which does the trick.
This snippet 'refreshes' the src of the embed iframe, causing it to reload:
jQuery(".modal-backdrop, #myModal .close, #myModal .btn").live("click", function() {
jQuery("#myModal iframe").attr("src", jQuery("#myModal iframe").attr("src"));
});
If someone still has the problem, try this, it worked for me:
$(document).ready(function(){
$('.modal').each(function(){
var src = $(this).find('iframe').attr('src');
$(this).on('click', function(){
$(this).find('iframe').attr('src', '');
$(this).find('iframe').attr('src', src);
});
});
});
Here is a simple way I've found for having a video play in a modal window, and then stop playing on close.
Use the .html to load the iFrame with your video into the modal-body, when the modal is shown, and then replace the modal-body with nothing when it is hidden.
$('#myModal').on('show', function () {
$('div.modal-body').html('YouTube iFrame goes here');
});
$('#myModal').on('hide', function () {
$('div.modal-body').html('');
});
Here is a jsfiddle example:
http://jsfiddle.net/WrrM3/87/
Here, I generalize #guillesalazar's answer.
This will reset any iFrame within any bootstrap modal (when the modal is closed):
$(function(){
$("body").on('hidden.bs.modal', function (e) {
var $iframes = $(e.target).find("iframe");
$iframes.each(function(index, iframe){
$(iframe).attr("src", $(iframe).attr("src"));
});
});
});
Add this to your layout and you're set.
UPDATE: Code modified for modals with multiple iFrames.
You should empty iframe src first and then set it up again.
So my working answer:
$('#myModal').on('hidden.bs.modal', function () {
var src = $(this).find('iframe').attr('src');
$(this).find('iframe').attr('src', '');
$(this).find('iframe').attr('src', src);
});
October, 2014. For Bootstrap 3.
Here is my solution, it solves the following using bootstrap event calls:
Autoplay movie when showing the modal
Stop movie when modal is hidden
HTML carousel inside modal, first active item is the iframe video
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Modal</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div id="myCarousel" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="fill">
<iframe id="videoIframe" width="100%" height="100%" src="https://www.youtube.com/embed/UVAjm8b7YFg?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript autoplay when displaying modal, then reset the URL and apply it to iframe src again
$('#myModal').on('show.bs.modal', function() {
$("#videoIframe")[0].src += "&autoplay=1";
});
$('#myModal').on('hidden.bs.modal', function(e) {
var rawVideoURL = $("#videoIframe")[0].src;
rawVideoURL = rawVideoURL.replace("&autoplay=1", "");
$("#videoIframe")[0].src = rawVideoURL;
});
This one does it perfectly:
$("#myModal").on("hidden.bs.modal", function(t) {
var o = $(t.target).find("iframe");
o.each(function(t, o) {
$(o).attr("src", $(o).attr("src"))
});
});
If you however want to have it start when modal opens / stop when it closes use this code:
But make sure to add enablejsapi=1 in your src, like this for example:
<iframe src="https://www.youtube.com/embed/YOUR_VIDEO_CODE?rel=0&controls=0&showinfo=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
function playStopVideo() {
var youtubeFunc ='';
var outerDiv = $("#myModal");
var youtubeIframe = outerDiv.find("iframe")[0].contentWindow;
outerDiv.on('hidden.bs.modal', function (e) {
youtubeFunc = 'stopVideo';
youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
});
outerDiv.on('shown.bs.modal', function (e) {
youtubeFunc = 'playVideo';
youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
});
}
playStopVideo();
A much easier way than all of these answers is just replacing the whole src. This works for all modals and you can adjust iframe class as required.
$('.modal').on('hidden.bs.modal', function(e) {
var closestIframe = $(e.currentTarget).find('iframe');
var rawVideoURL = $("iframe")[0].src;
closestIframe[0].src = "";
closestIframe[0].src = rawVideoURL;
});
Reload any iframe in bootstrap modal on hide.bs.modal event.
The setTimeout delay added for fixing iframe rendering after src reset.
$('.modal').on('hidden.bs.modal', function (event){
let iframes = event.target.getElementsByTagName('iframe');
for (let i = 0; i < iframes.length; i++) {
let src_tmp = iframes[i].src;
iframes[i].src = '';
setTimeout(() => {
iframes[i].src = src_tmp;
}, 100);
}
});
I used a combination of Ruslanas Balčiūnas and Nathan McFarland's answers to code something that worked well for me.
$('#myModal').on('hide',function(){
$('.modal-body iframe').attr('src','');
});
So basically this sets the src attribute of the iframe to nothing when the close modal event is triggered. Short and sweet.
My solution to this that works for Bootstrap 3 and the modern YouTube embed format is as follows.
Assuming your video is embedded within a standard Bootstrap 3 Modal with id="#video-modal", this simple bit of Javascript will do the job.
$(document).ready(function(){
$("#video-modal").on('hide.bs.modal', function(evt){
var player = $(evt.target).find('iframe'),
vidSrc = player.prop('src');
player.prop('src', ''); // to force it to pause
player.prop('src', vidSrc);
});
});
I've seen proposed solutions to this issue involving use of the YouTube API, but if your site is not an https site, or your video is embedded using the modern format recommended by YouTube, or if you have the no-cookies option set, then those solutions don't work and you get the "TV set to a dead channel" effect instead of your video.
I've tested the above on every browser I could lay my hands on and it works very reliably.
Expanding on Guille's answer above, this is a drop-in function that will work with Bootstrap 3, the latest version of youtube as of Aug 14, and works for multiple videos /modals in one page.
$(".modal").on('hidden.bs.modal', function(e) {
$iframe = $(this).find( "iframe" );
$iframe.attr("src", $iframe.attr("src"));
});
Had a modal with many videos. Updated the code by #guillesalazar to close multiple videos in the modal.
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").each(function () {
$(this).attr("src", '');
});
});
7 years after, we still need to solve this.
We found a best way to fix it (Inspired by RobCalvert123 answer)
jQuery(".modal-backdrop, .modal.open .close,.modal.open .btn").live("click", function() {
// Get iframe opened
var iframe_open = jQuery('.modal.open');
// Get src from opened iframe
var src = iframe_open.attr('src');
// replace src by src to stop it that's the tips
iframe_open.attr("src", src);
});
1. Embed Youtube on your Page (html)
Add the Youtube div-container to your Website:
<div id="ytplayer">This will be replaced with the Youtube iFrame</div>
Add the Youtube Javascript Api (iFrame)
<script>
// Ads Youtube JS API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'ncif63mSZl4',
WMode: 'transparent',
wmode: 'opaque',
playerVars: {
'autoplay': 0,
'controls': 0,
'autohide':1,
'rel':0,
'showinfo': 0,
'modestbranding': 1,
},
});
}
function stopVideo() {
player.stopVideo();
}
function pauseVideo() {
player.pauseVideo();
}
function playVideo(){
player.playVideo();
}
</script>
Controll with jQuery (Bootstrap Modal)
// Open Modal and start Playing Youtube Video
$("#myModalTrigger").click(function(){
$("#video-modal").modal(); // opens up the Modal
playVideo(); // Starts playing Video
});
// Stop Player on Modal hide
$('#video-modal').on('hide.bs.modal', function (e) {
stopVideo(); // stop player
});
$('#myModal').on('hide', function () {
$('#video_player')[0].stopVideo();
})
#guillesalazaar's answer was only the 1st half of my fix so I felt compelled to share my situation in case it helps someone in the future. I too have an embedded youtube video but I set mine to play automatically when the frame is loaded using autoplay=1. To get around the autoplay issue on page load I have my youtube url stored in a variable that sets the iframe source using a click handler. To solve this I simply removed the attribute source link:
My Url to trigger the modal window:
<div id="movieClick" class="text-center winner">
<a href="#" data-toggle="modal" data-keyboard="true" data-target="#movie">
</div>
My hidden modal window divs:
<div id="movie" class="modal fade" role="dialog" tabindex='-1'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">They Live (1988)</h4>
</div>
<div class="modal-body">
<iframe id="onscreen" width="100%" height="460px" src="" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
My JS:
$("#movieClick").click(function(){
var theLink = "https://www.youtube.com/embed/Wp_K8prLfso?autoplay=1&rel=0";
document.getElementById("onscreen").src = theLink;
});
// really annoying to play in the Background...this disables the link
$("#movie").on('hidden.bs.modal', function (e) {
$("#movie iframe").attr("src", '');
});
//stop youtube video on modal close
$('.modal').on('hidden.bs.modal', function () {
var iframVideo = $('.modal').find('iframe');
$(iframVideo).attr("src", $(iframVideo).attr("src"));
});
My solution for 2 or more Youtube videos using the HTML data-* attribute. The video autoplays and stops when the modal is opened and closed.
<button data-url="https://www.youtube.com/embed/C0DPdy98e4c" data-toggle="modal" data-target="#mymodal">Video 1</button>
<button data-url="https://www.youtube.com/embed/ScMzIvxBSi4" data-toggle="modal" data-target="#mymodal">Video 2</button>
<!-- Modal -->
<div id="mymodal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
$('.modal').on('show.bs.modal', function (event) {
$(this).find('iframe').attr("src", $(event.relatedTarget).data('url') );
});
$('.modal').on('hidden.bs.modal', function (e) {
$(this).find('iframe').attr("src", "");
});
Here is a Codepen demo:
https://codepen.io/danielblazquez/pen/oOxRJq
For angular or for dynamic html or if we have multiple iframes then use as below
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").each(function(){
$(this).attr("src", $(this).attr("src"));
});
});
if you have multiple modals with many videos, let's say you have a modal on each slide on a carousel for instance, you need something more dynamic to close/stop the video in the visible slide and not mess up all the other modals, use this:
$(".modal").on('hidden.bs.modal', function (e) {
$(this).find("iframe").attr("src", $(this).find("iframe").attr("src"));
});

Categories