Technology Temerity

Bootstrap Remote File Modals

Introduction

Opening a modal is well documented for the Bootstrap framework when the modal’s contents are located within the same document. However, if the modal content is stored in a remote file, the process becomes slightly more nebulous. After some experimenting and Stack Overflow research, I compiled the following steps.

Link

The link for opening a modal must still target a container element of some sort, typically a DIV id. You may also choose to target the container by class. For remote files, you need to include an href attribute as well, targeting the remote file location.

<a href="modal_document.php" data-target="#modal_div_container_id" data-toggle="modal">Open Modal</a>

Modal Container

Next you need to prepare the calling document (the same document that contains the modal link) with a modal container. This is exactly the same as with a normal modal, except you are only adding the modal’s container elements, not its content.

<div class="modal fade" id="modal_div_container_id">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal content area - leave this empty.-->
        </div>
    </div>
</div>

Modal Document (Content)

The last step is to prepare your remote document. Add whatever content you wish. The only special caveat to consider is you do NOT add the modal container elements to this document. You only add the content. The content itself may include its own container elements, formatting, and so forth. In the example below, the modal is a simple list, and therefore only the markup for the list is included.

<ul>  
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

You’ve probably already guessed what’s going on here. When the modal link is clicked, Bootstrap loads the remote document’s contents and injects them into the .modal-content element inside the targeted modal container. Bootstrap Modal Documentation (extracted 2017-01-23):

If a remote URL is provided, content will be loaded one time via jQuery’s load method and injected into the .modal-content div. If you’re using the data-api, you may alternatively use the href attribute to specify the remote source.

This is why you must include a target element in the calling document, and conversely NOT include modal containers in the remote document. Hope this helps. Special thanks to Buzinas from Stack Overflow.

Until next time!

DC

Author: Damon Caskey

Hello all, Damon Caskey here - the esteemed owner of this little slice of cyberspace. Welcome!

Leave a Reply