SHARE
Facebook X Pinterest WhatsApp

Bootstrap 3 Modal: Create a Timed Alert and Video Player

Written By
thumbnail
Rob Gravelle
Rob Gravelle
Aug 3, 2017

In the Customizing Bootstrap Modals tutorial, we learned how to change a Modal’s position, size, header color, as well as add responsiveness using JavaScript (JS). That article focused on Modals that essentially replaced the default JS alerts. But why stop there when Modals can contain any HTML content? In today’s follow-up, we’re going to look at some other uses for Modals, specifically a timed alert and video player.

Creating a Timed Alert

Bootstrap Modals aren’t just a better-looking version of a JS alert; they offer event handlers that offer us much more fine-grained control over their behavior. For instance, we can dismiss the Modal after a certain amount of time has elapsed using a timer.

Take a look at the following button and Modal code and notice that the Modal DIV is very basic, with only the content DIV. In it, we’ll display a CSS loading wheel, a message, and a countdown:

<!-- Button triggered modal -->
<p><button type="button" 
        class="btn btn-primary btn" 
        data-toggle="modal" 
        data-target="#timedAlert">
  Click to open a timed alert
  </button></p>

<div id="timedAlert" tabindex="-1" class="modal fade" role="dialog" aria-labelledby="timedAlert" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <div><div class="loadersmall"></div>We control the vertical and the horizontal. Please stand by for <span> </span>...</div>
      </div>
    </div>
  </div>
</div>

The JavaScript code is responsible for:

  1. setting the starting count
  2. launching the countdown via the setInterval() function
  3. clearing the count when the Modal is dismissed

One of the challenges of keeping track of the timer is that global variables don’t work very well with event handlers due to their delayed invocation. The solution is to store the counter id in the Modal’s data property.

Inside the setInterval()’s anonymous function, we have the same problem of delayed invocation for the Modal object. This time we can solve it by passing it directly to the setInterval() function as the optional third argument. After updating the count we hide the Modal if the remaining time has reached zero.

var DISPLAY_TIME = 5;
$('#timedAlert')
  .on('show.bs.modal', function() {
    $(this).find('.modal-body span').text(DISPLAY_TIME);
}).on('shown.bs.modal', function () {  
    var countdownTimer = setInterval(function(timedAlert){
      var spanElt  = timedAlert.find('.modal-body span'),
          timeLeft = parseInt(spanElt.text());
      $('.modal-body span').text(--timeLeft);
      if (timeLeft <= 0) timedAlert.modal('hide');
    },1000, $(this));
    $(this).data('countdownTimer', countdownTimer);
}).on('hidden.bs.modal', function() {
  clearInterval($(this).data('countdownTimer'));
});

There is some CSS required to set the Modal width, center the contents and show the spinner.

#timedAlert .modal-dialog  { 
  width: 470px; 
  text-align: center;
}

.loadersmall {
    float: left;
    margin-right: 5px;
    border: 5px solid #f3f3f3;
    -webkit-animation: spin 1s linear infinite;
    animation: spin 1s linear infinite;
    border-top: 5px solid #555;
    border-radius: 50%;
    width: 20px;
    height: 20px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
} 

Here is a screenshot of the timed alert in action:

timed_alert (27K)

Of course, you can’t get much of a feel for it from an image, so I’ve posted a working demo in Codepen.

Displaying a YouTube Video in a Modal

Another common use of Bootstrap Modals is to display YouTube videos. On the surface, it would seem to be very easy to do; you just include the embed code in the content section of your Modal:

<div class="modal-body">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/wH_XuDA9eHc" frameborder="0" allowfullscreen></iframe>
</div>

The challenge is stopping the video when the Modal is dismissed. The simplest way to interrupt the video playback is to set the iFrame’s src to an empty string (”). Problem solved! That is, unless you want to play the video again. We’ve now lost the URL!

The solution again is to store the video URL as a data property. To do that, we must check the embedded iFrame’s src attribute. If the URL is there, we store it for later use; otherwise, we can fetch it from the data store:

$(function(){
    //Get iframe src attribute value 
    //i.e. YouTube video url
    $("#youtubeModal").on('show.bs.modal', function(){
        var modal = $(this),
            video = modal.find('iframe'),
            url   = video.attr('src');
        if (url) {
          //store url for later use
          modal.data('videoURL', url);
        }
        else {
          //fetch the url from the data store
          video.attr('src', modal.data('videoURL'));
        }
    }).on('hide.bs.modal', function(){
        //Assign empty url value to the iframe 
        //src attribute when modal is hidden, 
        //which stops the video playback
        $(this).find("iframe").attr('src', '');
    });
});

Here’s a screenshot of the video demo:

youtube_video (62K)

Conclusion

In today’s tutorial, we looked at two common uses for Bootstrap 3 Modals: a timed alert and video player. In the next installment, well learn how to include visual elements in our Modals, such as Glyphicons.

Recommended for you...

How to Make Your Site Voice Search Ready
Working with the CSS Image Gallery
HTML Geolocation: How to Find Someone’s Location
Octavia Anghel
Dec 10, 2018
Ten Basic Things Every Web Developer Should Know
Bradley Jones
Dec 3, 2018
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.