The Bootstrap 5 Modal does not open until the AJAX Content is loaded. It's a bad UX for my users as users have to wait few seconds for the modal to open after clicking the View
button!
So having said that, how can I load the Bootstrap 5 modal load instantly on clicking? Let the AJAX content take 2-3 ore more seconds to load after the modal is opened.
This is the button which triggers the modal: <button data-id="269" class="view-post">View</button>
Here's the JS code that loads the modal content:
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
$('#postModal h5#postModalLabel').text(response.title);
$('#postModal .modal-body').html(response.content);
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
postModal.show();
});
});
});
Not used jQuery for a long while, but you should be able to show the dialog, pre-fill with some loading indicator etc, call your ajax, and then when that's complete fill with the new data.
eg.
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
//lets have a reference to title & body element
var title = $('#postModal h5#postModalLabel');
var body = $('#postModal .modal-body');
//create our modal dialog
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
//pre-populate with some loading info.
title.text('Loading..');
body.html('Please wait.');
//now show dialog
postModal.show();
//now call ajax post
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
//now update dialog with new data.
title.text(response.title);
body.html(response.content);
});
});
});