Displaying JavaScript Modal Windows using Bootstrap
This page may contain links from our sponsors. Here’s how we make money.
This article is several years old and the techniques covered in the article may be outdated.
It is true that Bootstrap has grown to include supporters from all around the globe. As there are plans for a Bootstrap 3 release I want to go into detail for one topic in particular. The Bootstrap JavaScript effects are not always useful to developers, so JS files are not necessary for running the whole framework. But they do provide quicker features to define common UI elements without having to reinvent the wheel.
I want to focus this tutorial on using modal windows within a typical webpage. We just need to include two files out of the Bootstrap framework. And the JS codes are not overly complicated to understand. My example demo allows users to dynamically update the background color, so this does admittedly have some more sample JS then you will need. But it is an excellent introduction to adding these brief components into any ordinary website.
Grabbing the Files
Start off by downloading a copy of Bootstrap directly from Github. This will include the “bootstrap.css” and “bootstrap.min.js” files which I’ve added into my own demo. If file size is a problem then you may download the bootstrap-modal.js file which only allows space for JavaScript related to modal windows. Additionally Jordan Schroter has released an extended Bootstrap modal class which includes responsive designs and some other nice features.
But I will be using the full bootstrap JS file which works exactly the same. Now we need to include these files into a default HTML5 layout. I have copied over my header codes which also reference similar external documents.
<!doctype html> <html lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Demo Modal Windows via Bootstrap</title> <meta name="author" content="Jake Rocheleau"> <link rel="shortcut icon" href="https://www.vandelaydesign.com/favicon.ico"> <link rel="icon" href="https://www.vandelaydesign.com/favicon.ico"> <link rel="stylesheet" type="text/css" media="all" href="css/bootstrap.css"> <link rel="stylesheet" type="text/css" media="all" href="css/default.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" charset="utf-8" src="js/bootstrap.min.js"></script> <script type="text/javascript" charset="utf-8" src="js/modals.js"></script> <!--[if lt IE 9]> <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head>
The core CSS file for this layout is called default.css. I have also included a few styles to overwrite the default Bootstrap designs for modal windows. Additionally we have an external file named modals.js which handles both custom modal windows. This file also has custom functions written by me to save time with the interface features. But we can get into the JavaScript later, first we should dive into the page body content and structure.
For more web development resources, please see:
- 30 Free Calendar and Datepicker jQuery Plugins
- 15 Subreddits for Coding and Programming Help
- 9 of the Best WordPress Page Builders
Webpage Body HTML
Two big components of the body section are the trigger buttons, plus the modal windows themselves. We should break down each piece starting with the button links.
<center> <a href="#modalwin" data-toggle="modal" class="btn btn-large">Display Window</a> <a href="#bgchangemodal" data-toggle="modal" class="btn btn-large">Update the Background</a> </center>
These are the two buttons you will find in the center of the demo page. Each one is linked to a modal window which is actually coded right into the HTML page. Bootstrap allows developers to either load modal windows using local HTML, or include a remote file via Ajax. Notice the href values are tied into IDs on each of the modal blocks.
<!-- first modal window --> <div id="modalwin" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <header class="modal-header"> <a href="#" class="close" data-dismiss="modal">x</a> <h3>Prepare to be Amazed <small>or easily amused :]</small></h3> </header> <div class="modal-body"> <p>This is a generic modal window, but look we can add images!</small></p> <p><img src="images/jim-dwight-the-office.png" alt="Jim and Dwight from NBC's The Office" title="Jim and Dwight" class="img-rounded"></p> <p>Close me by clicking anywhere outside the window, or by clicking the blue button.</p> <p></p> </div> <footer class="modal-footer"> <a href="#" class="btn btn-primary" id="okwin01">Sounds Good!</a> </footer> </div> <!-- @end @modalwin -->
My first sample is just basic text with an image file. Bootstrap provides a standard for creating modal windows using three different sections: .modal-header, .modal-body, and .modal-footer. Each class may be attached onto any HTML element and it should display the same. You’ll also notice a small X in the corner with an anchor attribute data-dismiss.
These tiny additions into the Bootstrap library make customizing modal windows super easy. All of the components are readily available, you will just need to memorize(or save) the codes. On the core outer DIV element you will find three different classes which are very important. It looks like class=”modal hide fade” to include all the default settings. Let’s take a peek at the 2nd modal window.
<!-- BG color modal window --> <div id="bgchangemodal" class="modal hide fade dark" role="dialog" aria-labelledby="bgModalUpdate" aria-hidden="true"> <header class="modal-header"> <a href="#" class="close" data-dismiss="modal">x</a> <h3>Update the Background <small>just pick a color below</small></h3> </header> <div class="modal-body"> <div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert">x</a> Select a radio button and save changes to see the difference. </div> <input type="radio" id="bgdefault" name="bgradio" checked="checked"> <label for="bgdefault"><span></span>Default Color</label> <input type="radio" id="bgpalegreen" name="bgradio"> <label for="bgpalegreen"><span></span>Pale Green</label> <input type="radio" id="bgwisteria" name="bgradio"> <label for="bgwisteria"><span></span>Wisteria</label> <input type="radio" id="bgsaffron" name="bgradio"> <label for="bgsaffron"><span></span>Saffron</label> <input type="radio" id="bgcarnation" name="bgradio"> <label for="bgcarnation"><span></span>Carnation Pink</label> </div> <footer class="modal-footer"> <a href="#" class="btn" id="closewin02">Cancel</a> <a href="#" class="btn btn-primary" id="okwin02">Save Changes</a> </footer> </div> <!-- @end #bgchangemodal -->
I have very similar classes and elements placed in the header and footer sections of this modal window, too. The internal body content has a small informational div with the class .alert-info. Bootstrap has these custom-coded for error alerts, warnings, and other dialog boxes. Now you’ll see I have added the class .dark onto the modal container.
Inside the page CSS document I’ve created a new set of rules to overwrite the default modal styles. Using the class .dark gives this modal window a richer experience and the custom input forms really contrast well off the darker colors. The original source is from this Net Tuts+ article which also works using checkboxes.
Unique CSS Styles
Since a lot of the resets have already been placed inside the default Bootstrap stylesheet, my custom document is not very long. We have some useful classes defining the custom inputs and defining the darker modal windows. It should not require any additional CSS to get modal windows working properly – but it is worth looking over my codes to see how you may skin your own modal themes.
/** Bootstrap Dark Modal Styles **/ .modal-open .modal, .btn:focus { outline: none !important; } .modal.dark { background-color: #2d3032; } .modal.dark .modal-body { background: #40464b; } .modal.dark .modal-header { background: #2d3032; border-bottom: 1px solid #2a2c2e; } .modal.dark .modal-header h1, .modal.dark .modal-header h2, .modal.dark .modal-header h3, .modal.dark .modal-header h4 { color: #ccc; } .modal.dark .modal-footer { background: #2d3032; border-top: 1px solid #2a2c2e; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; }
I have followed a specificity which is adopted from the original Twitter Bootstrap CSS file. We need to ensure that each selector is nested deep enough to become the primary rendering block. I’ve included the !important keyword within a couple of properties which were not displaying properly. But the custom class provides a more branded feeling to your website.
Displaying Modals with JavaScript
We should jump right into my customized JS file modals.js which will explain how we can piece the HTML links and hidden windows together. Since we are looking at both jQuery and Bootstrap framework codes, I will break down individual snippets to explain in detail.
$(function(){ function hideModal(modalwindow){ $(modalwindow).modal('hide'); }
This will open the jQuery DOM check and defines a brand new function called hideModal(). The internal parameter is a jQuery selector pointing at the modal window to hide. This small chunk of code which will save us time when calling the same function over again.
$('#okwin01').on('click', function(e){ e.preventDefault(); hideModal('#modalwin'); }); $('#okwin02').on('click', function(e){ e.preventDefault(); updateBGColor(); hideModal('#bgchangemodal'); });
The two IDs #okwin01 and #okwin02 are targeting specific buttons within the two windows. These are both the ‘OK’ button which hides the form. When they are clicked we need to reference the hideModal() function I wrote earlier. But the 2nd window also calls another function named updateBGColor(). This will determine the currently selected radio input and change the body background color accordingly. Shouldn’t matter if you understand those codes but it is a neat little script.
$('#closewin02').on('click', function(e){ e.preventDefault(); var currentbg = rgb2hex($('body').css('backgroundColor')); resetRadioBtns(currentbg); hideModal('#bgchangemodal'); }); });
This is the last interesting piece to our jQuery modal functions and will run after the user clicks ‘Cancel’ in the BG color modal window. You will find all the other functions we were using, plus a new set of commands used for resetting the input values. If the user opens our modal window and changes input values without saving, then cancels, we just reset back to the currently selected value based on the current body BG color. It is all straightforward once you get the hang of reading through functions. But check out my sample code as a reference guide.
Final Thoughts
Bootstrap is a tremendous library which is full of distinct widgets & design features. You could spend weeks toying around with all of the various pieces of Bootstrap. And the basic CSS resets do help to jumpstart projects which are on a strict timeframe.
Ideally you should be able to replicate much of the same codes displayed here to get your own modal windows in Bootstrap. But definitely grab a copy of my source code which you may compare with your own when running into trouble. There actual Bootstrap documentation is very well-designed and easy to read. If you have additional questions or suggestions feel free to share with us in the post discussion area.