Kris van der Mast
Kris van der Mast

Reputation: 16613

How to delay showing the header of a modal until an ajax call has returned in Twitter bootstrap?

I am using plain vanilla twitter bootstrap modals like:

<a data-toggle="modal" data-id="983E46EC-9DFE-4E5F-80E3-524C982FCC67" title="" class="open-signal btn btn-primary" href="#addSignal">Add signal</a>

The data-id is used in a small piece of jQuery to make an ajax request, render out some html and then inject that into the modal-body div:

$(document).on('click', '.open-signal', function () {
    var id = $(this).data('id');
    $.get('@Url.Action("CreateSignal")', { "id": id })
        .done(function (d) {
            $('.modal-body', '#addSignal').html(d);
            $('#addSignal').modal('show');                    
        });
    });

However the header and footer of the modal already show while the ajax call, could be several seconds or longer, already shows and only if the ajax call is done it injects the retrieved html.

How can I delay the modal (header + footer) to appear entirely until the ajax call has finished?

Upvotes: 0

Views: 305

Answers (2)

Colin
Colin

Reputation: 22595

The Bootstrap documentation has an example that uses the show.bs.modal event as the trigger to load ajax into a modal dialog rather than the click event on the opener. I've modified that pattern in my solution:

$('#mainModal')
    .on('show.bs.modal', function (e) {
        var $source = $(e.relatedTarget);
        var $modal = $(this);
        var title = $source.data('modalTitle'); //data-modal-title="@item.Name"
        var url = $source.attr("href"); //assumes source is a hyperlink

        if (title && url) {
            $modal.find('.modal-title').text(title);
            $modal.find(".modal-body").load(url, function () {
                //the call to modal('show') triggers the event again, 
                //but the $source won't have a title or an href
                $modal.modal('show'); 
                $modal.find('.modal-body input').first().focus();
            });

            //don't show the dialog immediately
            return e.preventDefault();
        }
    });

Upvotes: 0

mccannf
mccannf

Reputation: 16659

Remove the data-toggle="modal" from the <a> tag. Note however, you should also catch .error on the $.get and provide feedback to the user, otherwise it will appear that clicking Add signal does nothing.

Example here: http://jsfiddle.net/mccannf/HK26K/2/

Upvotes: 1

Related Questions