user1996496 user1996496 - 2 months ago 6
Javascript Question

How do I delay the loading of a Boostrap modal until the remote content is loaded?

I am loading content remotely like this:

$('a[rel=modal]').on('click', function(evt) {
evt.preventDefault();
var modal = $('#modal').modal();
modal
.find('.modal-body')
.load($(this).attr('href'), function (responseText, textStatus) {
if ( textStatus === 'success' ||
textStatus === 'notmodified')
{
modal.show();
}
});
});


The problem is that the modal shows and 1-2 seconds later the content shows inside and expands the modal, so it's kind of "jumpy". Is there a way to delay the loading of the modal until after the content has been received?

Answer

Summer Developer is correct in their comment. Your modal is being displayed by $('#modal').modal(); before you make the request. You should instead show the modal in the callback function for .load(), which fires after the request is complete. Here is how you can make it work with minimal changes to your code:

$('a[rel=modal]').on('click', function(evt) {
    evt.preventDefault();
    var modal = $('#modal');
    modal
        .find('.modal-body')
        .load($(this).attr('href'), function (responseText, textStatus) {
            if ( textStatus === 'success' || 
                 textStatus === 'notmodified') 
            {
                modal.modal("show");
            }
    });
});

Notice I remove the .modal() call from the jquery object and then I use modal.modal("show") which is probably what you were trying to do (instead of .show())

Comments