I recently experimented with modal using Bootstrap 4 from a code I found on this website
<div class="container">
<h1>Experience Playing YouTube or Vimeo Videos in Bootstrap 4 Modal</h1>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/Jfrjeg26Cwk" data-target="#myModal">
Play Video 1
</button>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/IP7uGKgJL8U" data-target="#myModal">
Play Video 2
</button>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/A-twOC3W558" data-target="#myModal">
Play Video 3
</button>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary video-btn" data-toggle="modal" data-src="https://player.vimeo.com/video/58385453?badge=0" data-target="#myModal">
Play Vimeo Video
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="" id="video" allowscriptaccess="always">></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
CSS styles :
body {margin:2rem;}
.modal-dialog {
max-width: 800px;
margin: 30px auto;
}
.modal-body {
position:relative;
padding:0px;
}
.close {
position:absolute;
right:-30px;
top:0;
z-index:999;
font-size:2rem;
font-weight: normal;
color:#fff;
opacity:1;
}
Javascript functionality :
$(document).ready(function() {
// Retrieves the video source from the data-src attribute of each button
var $videoSrc;
$('.video-btn').click(function() {
$videoSrc = $(this).data( "src" );
});
console.log($videoSRC);
// Autoplay the video when modal is opened
$('#myModal').on('shown.bs.modal', function (e) {
// Set the video source to autoplay and hide related videos. Prevent annoying surprises!
$("#video").attr('src',$videoSrc + "?rel=0&showinfo=0&modestbranding=1&autoplay=1" );
})
// Stop playing the Youtube video when modal is closed
$('#myModal').on('hide.bs.modal', function (e) {
// Simple way to stop the video
$("#video").attr('src',$videoSrc);
})
// Document ready function
});
The modal does not appear when tested on localhost. Can anyone suggest a solution for this issue? Your help would be greatly appreciated.
Note: The code has been edited slightly.
Below are the links to the CSS and Javascript files used locally: