Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Dynamically Creating and Showing Bootstrap Modal

4.50/5 (3 votes)
18 Oct 2015CPOL2 min read 28.5K  
Dynamically creating and showing Bootstrap Modal

Yes I do agree Bootstrap is very cool. Well at-least for a developer you don’t have to mess with a lot of CSS figuring out responsiveness mobile friendly and a cool design. There may be a lot of other reasons for you to like it but personally I like it because it is now a fully matured framework and also you get a very active community for help.

And recently, I was using bootstrap’s Modal quite heavily. So I had to write a lot of code in JavaScript and during the process also wrote this small piece of code to create and show bootstrap modal at run-time in JavaScript having dynamic title, body and buttons. Thought of sharing here if anyone needs it, though most of us may have it already in our code repositories but still no harm in sharing right :).
OK, here are some details about these functions:

JavaScript
BstrapModal function (title, body, buttons)

BstrapModal class has a single constructor which takes these three parameters - title, body and buttons.

  • Title: Title of the Modal. It can be both html or simple string.
  • Body: Body of the Modal. It can also be html or string.
  • Buttons: Buttons in the footer of the Modal. It is an array of the Button Object. Button object should have Value, Css and Callback function of the button. Value is just the display text of the button while Callback function would be executed on clicking the button, e.g., a button object would look like this:
    JavaScript
     {Value:"CLOSE", Css:"btn-danger", 
    Callback:function(event){/*Close button click logic*/ }} 

BstrapModal.Close will close the modal and delete it from document.

You can extend this class with your requirements, e.g, for different bootstrap button types, you can create an enum and put in the constructor. Or you can extend show function so it can get the modal type like large or small, etc.

JavaScript
var BstrapModal = function (title, body, buttons) {
    var title = title || "Lorem Ipsum History", body = body || 
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
    when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
    It has survived not only five centuries, but also the leap into electronic typesetting, 
    remaining essentially unchanged.", buttons = buttons || [{ Value: "CLOSE", 
    Css: "btn-primary", Callback: function (event) { BstrapModal.Close(); } }];
    var GetModalStructure = function () {
        var that = this;
        that.Id = BstrapModal.Id = Math.random();
        var buttonshtml = "";
        for (var i = 0; i < buttons.length; i++) {
            buttonshtml += "<button type='button' class='btn " + 
            (buttons[i].Css||"") + "' name='btn" + that.Id + 
            "'>" + (buttons[i].Value||"CLOSE") + 
            "</button>";
        }
        return "<div class='modal fade' name='dynamiccustommodal' 
        id='" + that.Id + "' tabindex='-1' role='dialog' 
        data-backdrop='static' data-keyboard='false' aria-labelledby='" + 
        that.Id + "Label'><div class='modal-dialog'>
        <div class='modal-content'><div class='modal-header'>
        <button type='button' class='close modal-white-close' 
        onclick='BstrapModal.Close()'><span aria-hidden='true'>&times;
        </span></button><h4 class='modal-title'>" + title + 
        "</h4></div><div class='modal-body'>
        <div class='row'><div class='col-xs-12 col-md-12 col-sm-12 col-lg-12'>" + 
        body + "</div></div></div><div class='modal-footer bg-default'>
        <div class='col-xs-12 col-sm-12 col-lg-12'>" + buttonshtml + 
        "</div></div></div></div></div>";
}();
    BstrapModal.Delete = function () {
        var modals = document.getElementsByName("dynamiccustommodal");
        if (modals.length > 0) document.body.removeChild(modals[0]);
    };
    BstrapModal.Close = function () {
        $(document.getElementById(BstrapModal.Id)).modal('hide');
        BstrapModal.Delete();
    };    
    this.Show = function () {
        BstrapModal.Delete();
        document.body.appendChild($(GetModalStructure)[0]);
        var btns = document.querySelectorAll("button[name='btn" + BstrapModal.Id + "']");
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", buttons[i].Callback || BstrapModal.Close);
        }
        $(document.getElementById(BstrapModal.Id)).modal('show');
    };
};

You can use this as:

JavaScript
new BstrapModal().Show();

This will show you the below modal, as we didn’t pass any title, body and buttons array, so it will use all default values:

BModal

I used Bootstrap v3.3.5 as you can see in this screen-cast from my project:

BstrapHierarchy

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)