Code: Dynamic Modal with Twitter Bootstrap and jQuery

UPDATE Sep 2013: I cleaned up the code a little. Please feel free to post comments, improvements, and questions.

High Level

I’ve found the need for a dynamic bootstrap modal that I could pass in the header text, body, and a callback function. I have a hidden DOM element called #scrap-modal that is stored in a universally accessible variable $msgModal. I then wrote a function showMsg that accepts a header and body text as well as a callback function. It adds the text to the modal, shows it, and then at the end calls your callback. Currently only accepts a success callback, you could easily add a cancel callback.

Code

HTML

<div id="scrap-modal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>HEADER TEXT IS PUT HERE</h3>
  </div>
  <div class="modal-body">
    BODY HTML IS PUT HERE
  </div>
  <div class="modal-footer">
    <a href="#" data-dismiss="modal" class="btn">Close</a>
    <a href="#" class="btn btn-primary callback-btn">
      btnSubmitText IS PUT HERE
    </a>
  </div>
</div>

JavaScript

var $msgModal = $('#scrap-modal').modal({
  backdrop: true,
  show: false,
  keyboard: false
});

showMsg = function (header, body, btnSubmitText, callback) {
  $msgModal
    .find('.modal-header > h3').text(header).end()
    .find('.modal-body').html(body).end()
    .find('.callback-btn').html(btnSubmitText).end()
    .find('.callback-btn').off('click.callback')
    .on('click.callback', function(){
      callback; 
      $msgModal.modal('hide');
     }).end()
    .modal('show');
};

Leave a Reply