25
Apr '20

Remote Bootstrap Modals The Easy Way

I make a lot of use of bootstrap modals in my code, and I find it incredibly useful to load the content dynamically, rather than have everything embedded in the page just in case it may be needed. To do this I tend to have a modal container (sometimes multiple, allowing for different sizes or styles), and target it from the trigger link.

<a href="/remote/content" class="btn btn-xs btn-primary modal-toggle" data-toggle="modal" data-target="#remote-modal" title="Load remote modal">Load Modal</a>

<div class="modal fade remote-modal" id="remote-modal" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">

        </div>
    </div>
</div>

Then all it takes is a modal show listener that grabs the URL from the trigger, and loads the content via AJAX into the modal-content section. This also gives me the opportunity to add a new modal event that is fired when the content has completed loading; ‘loaded.bs.modal’. This new event is hugely useful as the core ‘shown.bs.modal’ event will often trigger before the content is loaded.

$('.remote-modal').on('show.bs.modal', function (e) {
    var trigger = $(e.relatedTarget);
    var modal = $(this);

    $(this).find('.modal-content').load(trigger.attr('href'), function() {
        modal.trigger('loaded.bs.modal', []);
    });
});

Simple as that.

Leave a Reply