Bootstrap modal manipulations made easy in Rails

Bootstrap modal

Modal is a kind of popup provided by bootstrap. But generally its a kind of clumsy task to handle different manipulations on it.

How we handle modal in application efficiently

  • Add the HTML code of modal in the layout file - app/views/layouts/application.html.erb
<div class="modal fade modal-window custom-popup" id="modal-window" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h3 class="modal-title"> Modal title </h3>
      <div class="modal-body custom-body">
        <div class="modal-body"><p>Modal body</p></div>
      <div class="modal-footer">Modal footer</div>
  • Now add a js file in - app/assets/javascripts/show_modal.js
function showModal(options) {
    if (options.animation == false) {
    if (options.dialog_class) {
    if (options.extra_class) {
    if (typeof(options.title) == 'undefined') {
    } else {
    if (typeof(options.footer) == 'undefined') {
    } else {

    if (typeof(options.callback_on_hidden) == 'function') {
        $('.modal').off('').on('', options.callback_on_hidden);
    if (typeof(options.callback_on_shown) == 'function') {
        $('.modal').off('').on('', options.callback_on_shown);
    $('.modal').on('', function () {
        if (options.animation == false) {
  • Now you just need to call the showModal(options) on the event you want where you want to show the modal anywhere in your application.
                title: 'Modal Title',
                content: $('<div>Modal Body</div>'),
                footer: 'Modal Footer',
                extra_class: 'extra_class_to_be_added_on_modal-header_div',
                callback_on_shown: function () {
                    console.log('JS code to be executed after the modal is shown')
                callback_on_hidden: function () {
                                    console.log('JS code to be executed after the modal is closed')

Doing this you will find the modal handling a fun in your application.

Thanks for reading!!!

comments powered by Disqus