0

I created a useful generic message box using javascript and bootstrap modal dialog. I (and potentially others) can use it anywhere. I would like to extract it into a js file, so that I can just refer to this js file in other projects. But I don't know how to include the HTML code block of the bootstrap modal dialog.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>A useful generic message box</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>


    <script type="text/javascript">
        function testAlert() {
            messageBox('Something went wrong!', 'error', null, function () {
                alert('Message dialog closed.');
            });
        }

        function testConfirm() {
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
                alert('"Yes" was selected.');
            });
        }

    function testPrompt() {
        messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (event) {
            alert('User entered "' + event.data.getUserInput() + '".');
        });
    }

        function messageBox(msg, significance, options, actionConfirmedCallback) {
            var okButtonName, cancelButtonName, showTextBox;

            if (options == null) {
                okButtonName = 'OK';
                cancelButtonName = null;
                showTextBox = null;
            } else {
                okButtonName = options.okButtonName;
                cancelButtonName = options.cancelButtonName;
                showTextBox = options.showTextBox;
            }
                

            if (showTextBox == true)
                $('#MessageDialogTextArea').show();
            else
                $('#MessageDialogTextArea').hide();

            //if (typeof (okButtonName) != 'undefined')
            if (okButtonName != null)
                $('#messageDialogOkButton').html(okButtonName);
            else
                $('#messageDialogOkButton').html('OK');

            //if (typeof (cancelButtonName) == 'undefined')
            if (cancelButtonName == null)
                $('#messageDialogCancelButton').hide();
            else {
                $('#messageDialogCancelButton').show();
                $('#messageDialogCancelButton').html(cancelButtonName);
            }

            $('#messageDialogOkButton').unbind('click');

            if (typeof (actionConfirmedCallback) != 'undefined')
                $('#messageDialogOkButton').on('click', { getUserInput: getUserInput }, actionConfirmedCallback);
            else
                $('#messageDialogOkButton').removeAttr('onclick');

            var content = $("#MessageDialogContent");

            if (significance == 'error')
                content.attr('class', 'text-danger');
            else if (significance == 'warning')
                content.attr('class', 'text-warning');
            else
                content.attr('class', 'text-success');

            content.html(msg);
            $("#MessageDialog").modal();
        }
    </script>
</head>

<body>


    <a href="#" onclick="testAlert();">Test alert</a> <br/>
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>
    <a href="#" onclick="testPrompt();">Test prompt</a>

    <div class="modal fade" id="MessageDialog" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p class="text-success" id="MessageDialogContent">Some text in the modal.</p>
                    <p><textarea id="MessageDialogTextArea" cols="70" rows="5"></textarea></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="messageDialogOkButton">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="messageDialogCancelButton">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</body>

</html>

2
  • 1
    Possible duplicate of include HTML code in js Commented Jun 29, 2016 at 1:31
  • You should use a templating engine. Commented Jun 29, 2016 at 1:33

2 Answers 2

1

It's not very idiomatic to do this, let alone reasonable. Never the less, assuming you don't need ES5 compliance, you could dump the whole thing into a template literal. Then you shove it into the dom somewhere within the script.

const template = `
    <div class="modal fade" id="MessageDialog" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p class="text-success" id="MessageDialogContent">Some text in the modal.</p>
                    <p><textarea id="MessageDialogTextArea" cols="70" rows="5"></textarea></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="messageDialogOkButton">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="messageDialogCancelButton">Cancel</button>
                </div>
            </div>
        </div>
    </div>
`

$('somehidden div').html(template);

Here is an ES5 version

    var template = '<div class="modal fade" id="MessageDialog" role="dialog">'+
    '    <div class="modal-dialog">'+
    '        <div class="modal-content">'+
    '            <div class="modal-body">'+
    '                <p class="text-success" id="MessageDialogContent">Some text in the modal.</p>'+
    '                <p><textarea id="MessageDialogTextArea" cols="70" rows="5"></textarea></p>'+
    '            </div>'+
    '            <div class="modal-footer">'+
    '                <button type="button" class="btn btn-primary" data-dismiss="modal" id="messageDialogOkButton">OK</button>'+
    '                <button type="button" class="btn btn-default" data-dismiss="modal" id="messageDialogCancelButton">Cancel</button>'+
    '            </div>'+
    '        </div>'+
    '    </div>'+
    '</div>';
$('somehidden div').html(template);

UPDATE

More maintainable solution:

Take this html and put it in it's own file modal.html.

   <div class="modal fade" id="MessageDialog" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p class="text-success" id="MessageDialogContent">Some text in the modal.</p>
                    <p><textarea id="MessageDialogTextArea" cols="70" rows="5"></textarea></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="messageDialogOkButton">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal" id="messageDialogCancelButton">Cancel</button>
                </div>
            </div>
        </div>
    </div>

Take your JS and put it in it's own file modal.js

      messageBox('Something went wrong!', 'error', null, function () {
            alert('Message dialog closed.');
        });
    }

    function testConfirm() {
        messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
            alert('"Yes" was selected.');
        });
    }

function testPrompt() {
    messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (event) {
        alert('User entered "' + event.data.getUserInput() + '".');
    });
}

    function messageBox(msg, significance, options, actionConfirmedCallback) {
        var okButtonName, cancelButtonName, showTextBox;

        if (options == null) {
            okButtonName = 'OK';
            cancelButtonName = null;
            showTextBox = null;
        } else {
            okButtonName = options.okButtonName;
            cancelButtonName = options.cancelButtonName;
            showTextBox = options.showTextBox;
        }


        if (showTextBox == true)
            $('#MessageDialogTextArea').show();
        else
            $('#MessageDialogTextArea').hide();

        //if (typeof (okButtonName) != 'undefined')
        if (okButtonName != null)
            $('#messageDialogOkButton').html(okButtonName);
        else
            $('#messageDialogOkButton').html('OK');

        //if (typeof (cancelButtonName) == 'undefined')
        if (cancelButtonName == null)
            $('#messageDialogCancelButton').hide();
        else {
            $('#messageDialogCancelButton').show();
            $('#messageDialogCancelButton').html(cancelButtonName);
        }

        $('#messageDialogOkButton').unbind('click');

        if (typeof (actionConfirmedCallback) != 'undefined')
            $('#messageDialogOkButton').on('click', { getUserInput: getUserInput }, actionConfirmedCallback);
        else
            $('#messageDialogOkButton').removeAttr('onclick');

        var content = $("#MessageDialogContent");

        if (significance == 'error')
            content.attr('class', 'text-danger');
        else if (significance == 'warning')
            content.attr('class', 'text-warning');
        else
            content.attr('class', 'text-success');

        content.html(msg);
        $("#MessageDialog").modal();

Use it in a document

<html>
<head>
  <script type="text/javascript>
    $(function() {
      $( body ).load( "path/to/modal.html" );
    });
  </script>
<script src="path/to/modal.js" type="text/javascript"></script>
</head>
Sign up to request clarification or add additional context in comments.

3 Comments

All I need is a way to make what I made, the bootstrap modal dialog and the messsageBox function, an external library, so that I don't have to duplicate the code block into every project I have. The goal is at least elegant isn't it? Whichever solution you think is elegant to achieve this elegant goal, I would embrace it. Since I am not javascript expert, could you please use my code to answer my question? Thanks!
You know you can edit an answer, right? That is, you could've made changes to your original answer rather than deleting it and posting a new one...
Updated Answer with a more maintainable solution. It's not tested but it should set you on the right path.
0

enter image description hereI worked out how to do it with the help of etherealite - his answer isn't complete but pointed to the right direction.

Now it is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

const dialogTemplate = '\
    <div class ="modal" id="digimango_messageBox" role="dialog">\
        <div class ="modal-dialog">\
            <div class ="modal-content">\
                <div class ="modal-body">\
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\
                </div>\
                <div class ="modal-footer">\
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\
                </div>\
            </div>\
        </div>\
    </div>';


// See the comment inside function digimango_onOkClick(event) {
var digimango_numOfDialogsOpened = 0;


function messageBox(msg, significance, options, actionConfirmedCallback) {
    if ($('#digimango_MessageBoxContainer').length == 0) {
        var iDiv = document.createElement('div');
        iDiv.id = 'digimango_MessageBoxContainer';
        document.getElementsByTagName('body')[0].appendChild(iDiv);
        $("#digimango_MessageBoxContainer").html(dialogTemplate);
    }

    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;

    if (options == null) {
        okButtonName = 'OK';
        cancelButtonName = null;
        showTextBox = null;
        textBoxDefaultText = null;
    } else {
        okButtonName = options.okButtonName;
        cancelButtonName = options.cancelButtonName;
        showTextBox = options.showTextBox;
        textBoxDefaultText = options.textBoxDefaultText;
    }

    if (showTextBox == true) {
        if (textBoxDefaultText == null)
            $('#digimango_messageBoxTextArea').val('');
        else
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);

        $('#digimango_messageBoxTextArea').show();
    }
    else
        $('#digimango_messageBoxTextArea').hide();

    if (okButtonName != null)
        $('#digimango_messageBoxOkButton').html(okButtonName);
    else
        $('#digimango_messageBoxOkButton').html('OK');

    if (cancelButtonName == null)
        $('#digimango_messageBoxCancelButton').hide();
    else {
        $('#digimango_messageBoxCancelButton').show();
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);
    }

    $('#digimango_messageBoxOkButton').unbind('click');
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);

    $('#digimango_messageBoxCancelButton').unbind('click');
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);

    var content = $("#digimango_messageBoxMessage");

    if (significance == 'error')
        content.attr('class', 'text-danger');
    else if (significance == 'warning')
        content.attr('class', 'text-warning');
    else
        content.attr('class', 'text-success');

    content.html(msg);

    if (digimango_numOfDialogsOpened == 0)
        $("#digimango_messageBox").modal();

    digimango_numOfDialogsOpened++;
}

function digimango_onOkClick(event) {
    // JavaScript's nature is unblocking. So the function call in the following line will not block,
    // thus the last line of this function, which is to hide the dialog, is executed before user
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do
    // not execute the last line in this function.
    if (typeof (event.data.callback) != 'undefined')
        event.data.callback($('#digimango_messageBoxTextArea').val());

    digimango_numOfDialogsOpened--;

    if (digimango_numOfDialogsOpened == 0)
        $('#digimango_messageBox').modal('hide');
}

function digimango_onCancelClick() {
    digimango_numOfDialogsOpened--;

    if (digimango_numOfDialogsOpened == 0)
        $('#digimango_messageBox').modal('hide');
}

To use digimango.messagebox.js:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>A useful generic message box</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>

    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>


    <script type="text/javascript">
        function testAlert() {
            messageBox('Something went wrong!', 'error');
        }

        function testAlertWithCallback() {
            messageBox('Something went wrong!', 'error', null, function () {
                messageBox('OK clicked.');
            });
        }

        function testConfirm() {
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });
            });
        }

        function testPrompt() {
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {
                messageBox('User entered "' + userInput + '".');
            });
        }

        function testPromptWithDefault() {
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {
                messageBox('User entered "' + userInput + '".');
            });
        }

    </script>
</head>

<body>
    <a href="#" onclick="testAlert();">Test alert</a> <br/>
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>
    <a href="#" onclick="testPrompt();">Test prompt</a><br />
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />
</body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.