Autoplay YouTube Video inside Bootstrap Modal
Topic: Bootstrap / SassPrev|Next
Answer: Add Remove Video Source URL with JavaScript
If try to autoplay YouTube video embedded inside Bootstrap modal through appending the video source url i.e. <iframe>
src
attribute value with ?autoplay=1
it will not work properly, because video is started playing before the modal is displayed.
To solve this problem you can add or remove the YouTube video source url based on whether the Bootstrap modal is displayed or not using the JavaScript. Let's see how it works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Autoplay YouTube Video in Bootstrap Modal</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.modal-content iframe{
margin: 0 auto;
display: block;
}
</style>
<script>
$(document).ready(function(){
/* Get iframe src attribute value i.e. YouTube video url
and store it in a variable */
var url = $("#cartoonVideo").attr('src');
/* Remove iframe src attribute on page load to
prevent autoplay in background */
$("#cartoonVideo").attr('src', '');
/* Assign the initially stored url back to the iframe src
attribute when modal is displayed */
$("#myModal").on('shown.bs.modal', function(){
$("#cartoonVideo").attr('src', url);
});
/* Assign empty url value to the iframe src attribute when
modal hide, which stop the video playing */
$("#myModal").on('hide.bs.modal', function(){
$("#cartoonVideo").attr('src', '');
});
});
</script>
</head>
<body>
<div class="bs-example">
<!-- Button HTML (to Trigger Modal) -->
<a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a>
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">YouTube Video</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="cartoonVideo" class="embed-responsive-item" width="560" height="315" src="//www.youtube.com/embed/YE7VzlLtp-4?autoplay=1" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic: