Skip to content

Tutorial: Playing YouTube Videos in Bootstrap Modal Dynamically Upon Click

play youtube videos in bootstrap modal

In this tutorial, we’ll explore how to create a visually appealing and responsive YouTube video player embedded within a Bootstrap modal and learn how to play YouTube videos in Bootstrap modal dynamically upon clicking on any element of your choice. We’ll utilize HTML, CSS, and JavaScript to achieve a sleek design, complete with a custom play icon and close functionality.

Demo: Playing YouTube Videos in Bootstrap Modal Dynamically Upon Click
Play Video in Modal

Let’s start creating a customized YouTube video player with Bootstrap modal.

Prerequisites:

Make sure you have the following dependencies included in your project:

  • Bootstrap CSS (version 4.5.2)
  • Bootstrap JavaScript (version 4.0.0)
  • Popper.js (version 2.5.2)
  • jQuery library (not required if you are trying this on WordPress site)

Step 1: Setting Up the HTML Structure

Embed the following bootstrap css file into the head tag of your page. If that is not possible then you can put it anywhere, it will work fine.

<!-- Include necessary Bootstrap and external dependencies -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

HTML Buttons to Trigger the Bootstrap YouTube Player Modal

<!-- HTML Buttons to Trigger the Bootstrap YouTube Player Modal -->

<div id="link" onclick="playVideo('Yppzo6dTpzY')" class="btn btn-primary">Play Video 1</div>
<div id="link" onclick="playVideo('WcIcVapfqXw')" class="btn btn-primary">Play Video 2</div>

These lines create two buttons, both with the class btn btn-primary for styling purposes. Each button has an onclick attribute, specifying a JavaScript function (playVideo) to be executed when the button is clicked.

The playVideo JavaScript function is called when either of the buttons is clicked. It takes a video ID as an argument, constructs the URL for embedding a YouTube video with autoplay, and sets it as the source for an iframe within a Bootstrap modal.

Bootstrap Modal Structure for YouTube Player

The following code defines the structure of a Bootstrap modal, which is a popup or dialog box often used for displaying additional content or functionality. Let’s break down the code:

<!-- Modal structure -->
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content bg-transparent border-0">
            <div class="border-0 justify-content-end modal-header p-0">
                <span onclick="stopVideo()" class=""><span aria-hidden="true" class="modalClose">×</span></span>
            </div>
            <div class="modal-body p-0 text-center">
                <div class="video-container">
                    <iframe width="1080" height="607" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" src="" frameborder="0" allowfullscreen=""></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

Let’s break down the components of this modal structure:

  1. Modal Container (<div class="modal" id="myModal">...</div>):
    • This is the main container for the Bootstrap modal.
    • id="myModal": Provides a unique identifier for the modal, which can be referenced in JavaScript or CSS.
    • tabindex="-1": Specifies that the modal can’t be navigated to via keyboard.
    • role="dialog": Indicates that the container serves the role of a dialog box.
    • aria-labelledby="myModalLabel": Connects the modal to an element with the specified label ID for accessibility purposes.
    • aria-hidden="true": Indicates that the modal is initially hidden.
  2. Modal Dialog (<div class="modal-dialog modal-lg modal-dialog-centered">...</div>):
    • This div represents the dialog box within the modal.
    • class="modal-dialog modal-lg modal-dialog-centered": Defines the modal size as large (modal-lg) and centers it on the page (modal-dialog-centered).
  3. Modal Content (<div class="modal-content bg-transparent border-0">...</div>):
    • The content within the modal, typically where your custom content goes.
    • class="modal-content bg-transparent border-0": Provides styling to make the modal background transparent and remove borders.
  4. Modal Header (<div class="border-0 justify-content-end modal-header p-0">...</div>):
    • The header section of the modal, typically containing a title and close button.
    • class="border-0 justify-content-end modal-header p-0": Removes borders, aligns content to the end, and removes padding.
  5. Close Button (<span onclick="stopVideo()" class=""><span aria-hidden="true" class="modalClose">×</span></span>):
    • A close button represented by an ‘×’ (multiplication symbol).
    • onclick="stopVideo()": Calls the stopVideo JavaScript function when clicked.
    • class="modalClose": Provides styling to the close button.
  6. Modal Body (<div class="modal-body p-0 text-center">...</div>):
    • The body of the modal where your custom content, in this case, a video container, is placed.
    • class="modal-body p-0 text-center": Removes padding (p-0) and centers the content horizontally (text-center).
  7. Video Container (<div class="video-container">...</div>):
    • A container for the embedded iframe, ensuring responsive scaling for the video.
    • class="video-container": Provides styling for responsive scaling.
  8. Embedded Iframe (<iframe width="1080" height="607" allow="..." src="" frameborder="0" allowfullscreen=""></iframe>):
    • An iframe element that can be used to embed a YouTube video.
    • width, height: Dimensions of the iframe.
    • allow: Specifies permissions for certain features (e.g., autoplay).
    • src: Initially empty; it will be dynamically set using JavaScript.
    • frameborder="0": Removes the border around the iframe.
    • allowfullscreen: Enables fullscreen mode for the embedded content.

In this step, we set up the HTML structure with buttons to trigger video playback and a modal container.

Step 2: Defining CSS Styles for Styling

<style type="text/css">
    /* Set the width of the video container to 100% */
    .video-container {
        position: relative;
        width: 100%;
        padding-bottom: 56.25%; /* 16:9 aspect ratio for responsive scaling */
    }

    /* Style the embedded iframe */
    .video-container iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .modal-dialog.modal-lg {
        width: 100% !important;
        max-width: 1080px !important;
    }

    .modal.show {
        display: flex !important;
        justify-content: center;
        align-items: center;
    }

    span.modalClose {
        font-size: 30px;
        font-weight: 700;
        color: #fff;
        cursor: pointer;
        line-height: 1;
    }

    span.modalClose:hover {
        color: var(--yellow) !important;
    }

    .play-icon:hover {
        border-width: 30px 0 30px 52.0px;
        cursor: pointer;
    }

    /* Styles for the play icon */
    .play-icon {
        width: 30px;
        height: 30px;
        border-style: solid;
        border-width: 20px 0 20px 33.0px;
        border-color: transparent transparent transparent red;
        position: absolute;
        transition: .2s;
    }
</style>

Here, we define CSS styles to customize the appearance of the video container, modal, close button, and play icon.

CSS Code Explanation
  1. Video Container Styles (.video-container):
    • Sets the width of the video container to 100%.
    • Uses relative positioning for the container.
    • Implements responsive scaling with a padding-bottom percentage based on a 16:9 aspect ratio.
  2. Embedded Iframe Styles (.video-container iframe):
    • Positions the embedded iframe absolutely within its container.
    • Ensures the iframe takes up the entire width and height of the container.
  3. Modal Dialog Styles (.modal-dialog.modal-lg):
    • Sets the width of the modal dialog to 100% and restricts the maximum width to 1080 pixels.
    • Ensures a responsive and visually balanced display on different screen sizes.
  4. Modal Display Styles (.modal.show):
    • Configures the modal to be displayed as a flex container.
    • Centers the content both horizontally and vertically within the modal.
  5. Close Button Styles (span.modalClose):
    • Defines styling for a close button represented by an ‘×’ (multiplication symbol).
    • Specifies a font size, font weight, color, and cursor appearance.
    • The button’s line-height is set to 1 for proper alignment.
  6. Close Button Hover Styles (span.modalClose:hover):
    • Provides styles for the close button when hovered.
    • Changes the color, creating a visual indication of interactivity.
  7. Play Icon Styles (.play-icon):
    • Sets the styling for a play icon, represented by a triangle.
    • Defines the width, height, border style, and color.
    • Uses absolute positioning within its container.
    • Implements a smooth transition effect over a duration of 0.2 seconds.
  8. Play Icon Hover Styles (.play-icon:hover):
    • Adds styles for the play icon when hovered.
    • Increases the border width, creating a visual feedback effect.

Step 3: Implementing JavaScript Logic

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<script type="text/javascript">
    // Play video in Bootstrap modal upon button click
    function playVideo(id) {
        var src = 'https://www.youtube.com/embed/' + id + '?autoplay=1&controls=0&rel=0';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    }
// Stop video in Bootstrap modal upon close icon click and hide the modal
    function stopVideo() {
        $('#myModal iframe').attr('src', '');
        $('#myModal').modal('hide');
    }
</script>

In this step, we include the necessary JavaScript files and define functions to play and stop the video. The playVideo function dynamically sets the YouTube video URL based on the provided video ID and displays the modal.

JavaScript Code Explanation

playVideo() : This function is responsible for initiating the playback of a YouTube video. Here’s a step-by-step explanation:

  • Parameters:
    • id: Represents the unique identifier of the YouTube video to be played.
  • Functionality:
    1. Construct URL:
      • Constructs the YouTube video URL using the provided video ID.
      • Appends query parameters (autoplay=1, controls=0, rel=0) to enable autoplay and customize controls.
    2. Show Modal:
      • Calls $('#myModal').modal('show') to display the Bootstrap modal with the ID “myModal.”
    3. Set Iframe Source:
      • Retrieves the iframe within the modal ($('#myModal iframe')).
      • Sets its source attribute to the constructed YouTube video URL ($('#myModal iframe').attr('src', src)).

stopVideo(): This function is responsible for stopping the YouTube video playback and hiding the Bootstrap modal. Here’s an explanation:

  • Functionality:
    1. Clear Iframe Source:
      • Sets the source attribute of the iframe within the modal to an empty string ($('#myModal iframe').attr('src', '')).
      • This action effectively stops the video playback.
    2. Hide Modal:
      • Calls $('#myModal').modal('hide') to hide the Bootstrap modal.

Complete Code to Play YouTube Videos in Bootstrap Modal

Below I have to the complete code for this tutorial. Just copy and save this code in a html file, for example, test.html You can just copy the code and paste it anywhere even in your wordpress post or page it will work just like it is working on this page.

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    </head>
<body>

<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <h1>Demo: Playing YouTube Videos in Bootstrap Modal Dynamically Upon Click</h1>
                <div onclick="playVideo('Yppzo6dTpzY')" class="btn btn-primary" >Play Video 1</div>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content bg-transparent border-0">
            <div class="border-0 justify-content-end modal-header p-0">
                <span onclick="stopVideo()" class=""><span aria-hidden="true" class="modalClose">×</span></span>
            </div>
            <div class="modal-body p-0 text-center">
                <div class="video-container">
                    <iframe width="1080" height="607" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" src="" frameborder="0" allowfullscreen=""></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- CSS Code -->
<style type="text/css">
    /* Set the width of the video container to 100% */
    .video-container {
        position: relative;
        width: 100%;
        padding-bottom: 56.25%; /* 16:9 aspect ratio for responsive scaling */
    }

    /* Style the embedded iframe */
    .video-container iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
    .modal-dialog.modal-lg {
        width: 100% !important;
        max-width: 1080px !important;
    }
    .modal.show {
        display: flex !important;
        justify-content: center;
        align-items: center;
    }
    span.modalClose {
        font-size: 30px;
        font-weight: 700;
        color: #fff;
        cursor: pointer;
        line-height: 1;
    }
    span.modalClose:hover {
        color: var(--yellow) !important;
    }


    .play-icon:hover {
     
      border-width: 30px 0 30px 52.0px;
      cursor: pointer;
    }

    /* Styles for the play icon */
    .play-icon {
      width: 30px;
      height: 30px;
      border-style: solid;
      border-width: 20px 0 20px 33.0px;
      border-color: transparent transparent transparent red;
          position: absolute;
      transition:.2s;
    }
</style>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
    //Play video in bootstra modal upon button click
    function playVideo(id) {
        var vid = id;
        console.log(id);
        var src = 'https://www.youtube.com/embed/'+id+'?autoplay=1&controls=0&rel=0';
        jQuery('#myModal').modal('show');
        jQuery('#myModal iframe').attr('src', src);
    }
    function stopVideo() {
       jQuery('#myModal iframe').attr('src', '');
        jQuery('#myModal').modal('hide');
        
    }
</script>
</body>
</html>

Conclusion

By following these steps, you’ve created a customized YouTube video player using Bootstrap, complete with responsive styling and interactive features. Feel free to adapt and extend this code to suit the specific needs of your project. Enjoy enhancing user experience with a stylish video playback solution!

Leave a Reply

Discover more from Oye Hoye AI

Subscribe now to keep reading and get access to the full archive.

Continue Reading