WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to embed YouTube video in Bootstrap modal

Topic: Bootstrap / SassPrev|Next

Answer: Insert YouTube Code inside Modal Body

You can easily embed or place the YouTube video inside a Bootstrap modal like you do on the normal web pages. Just get the code to embed the video from YouTube site and place it inside the .modal-body element. But there is small problem; the YouTube video doesn't stop automatically when you close the modal window. It will still play in the background.

To solve this problem you can simply toggle the url value of the YouTube's video iframe src attribute dynamically using the jQuery. Let's try out the following example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Insert 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>
<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');
    
    /* 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', '');
    });
    
    /* Assign the initially stored url back to the iframe src
    attribute when modal is displayed again */
    $("#myModal").on('show.bs.modal', function(){
        $("#cartoonVideo").attr('src', url);
    });
});
</script>
</head>
<body>
<div class="m-4">
    <!-- Button HTML (to Trigger Modal) -->
    <a href="#myModal" class="btn btn-primary btn-lg" 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">&times;</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" allowfullscreen></iframe>
                  </div>
                </div>
            </div>
        </div>
    </div>
</div>     
</body>
</html>

Please check out the tutorial on HTML5 video to learn about the various techniques of inserting videos on the web pages including the widely used YouTube videos.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties