Displaying content in Bootstrap 5 modal with jQuery may cause a delay in the appearance of a centered spinner before the content loads

In my Bootstrap 5 modal, I have implemented specific functionality in jQuery where a centered spinner is supposed to show up in the modal before loading the content. You can see a live example of this here.

The issue I am facing is that the spinner takes time to display when the modal is opened, instead of showing up instantly before loading the content. To better understand the problem, check out the example link provided.

When I click the button, the spinner does not appear quickly. Instead, the content is displayed first, followed by the spinner, which is not the correct behavior.

Live Example: https://codepen.io/themes4all/pen/vYmeXpy

jQuery Code:

(function ($) {
    "use strict";

    $(window).on("load", function () {
        if ($(".modal").length) {
            $(".modal").modal("show");
            $(".modal").on("shown.bs.modal", function (e) {
                e.preventDefault();
                $(".spinner")
                    .removeClass("d-none")
                    .delay(3000)
                    .fadeOut(500, function () {
                        $(this).addClass("d-none");
                    });
                return false;
            });
            $(".btn-close").on("click", function (e) {
                e.preventDefault();
                var swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: "btn btn-primary",
                        cancelButton: "btn btn-danger me-3",
                    },
                    buttonsStyling: false,
                });
                swalWithBootstrapButtons
                    .fire({
                        title: "Are you sure?",
                        text: "You won't be able to revert this!",
                        icon: "warning",
                        confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
                        cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
                        showCancelButton: true,
                        reverseButtons: true,
                        focusConfirm: false,
                    })
                    .then((result) => {
                        if (result.isConfirmed) {
                            $(".modal").modal("hide");
                        }
                    });
                return false;
            });
        }
    });
})(window.jQuery);

Answer №1

Check out the live example

If you're currently trying to get rid of the .d-none class (which sets display: none!important) on the spinner, you might notice that it's causing a delay in content loading. The recommended approach is actually the opposite: have the spinner visible by default and then hide it once the content is loaded. Therefore, you should remove all classes that apply display !important (such as d-flex, d-none), hide the spinner when the content loads, and then display it again when the modal is closed.

Here is the additional CSS that should be added:

.spinner {
  display: flex;
}

And here is the jQuery code to achieve this functionality:

(function ($) {
    "use strict";

    $(window).on("load", function () {
        if ($(".modal").length) {
            $(".modal").modal("show");
            $(".modal").on("shown.bs.modal", function (e) {
                e.preventDefault();
                $(".spinner")
                    .delay(3000)
                    .fadeOut(500);
                return false;
            });
            $(".btn-close").on("click", function (e) {
              
                e.preventDefault();
                var swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: "btn btn-primary",
                        cancelButton: "btn btn-danger me-3",
                    },
                    buttonsStyling: false,
                });
                swalWithBootstrapButtons
                    .fire({
                        title: "Are you sure?",
                        text: "You won't be able to revert this!",
                        icon: "warning",
                        confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
                        cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
                        showCancelButton: true,
                        reverseButtons: true,
                        focusConfirm: false,
                    })
                    .then((result) => {
                        if (result.isConfirmed) {
                          $(".modal").modal("hide");
                          $(".spinner").delay(1000).show(100);
                        }
                    });
                return false;
            });
        }
    });
})(window.jQuery);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert JSON data into an HTML table with custom styling

If you have a set of JSON data that you want to convert into an HTML table, you can use the following code: $.each(data, function(key, val) { var tr=$('<tr></tr>'); $.each(val, function(k, v){ $('<td>' ...

Struggling to retrieve scope data within directive from controller in AngularJS

As a newcomer to AngularJS, I have utilized a service to retrieve data from the backend and received it in the controller. Now, my task is to parse these values and dynamically generate elements in a directive. However, when attempting to do so, I am encou ...

Interactions with the mouse while using the window.alert and window.confirm features

Currently, I have developed a custom drag method that utilizes mousedown, mouseup, and mousemove events. This method is defined as move(). $(document).on('mousedown', function() {drag = true }); $(document).on('mouseup', function() {dr ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...

The dilemma between Nuxt Js global CSS and Local CSS

Currently, I am in the process of developing a Nuxt application utilizing an admin template. While I am well-versed in Vue.js, I am finding the aspect of loading assets within Nuxt.js to be a bit perplexing. I am in the process of converting the admin temp ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Using Javascript to Divide Table into Separate Tables each Containing a Single Row

Is there a way to divide the content of this table into three separate tables using JavaScript? It is important that each table retains its header information. Unfortunately, I am unable to modify the id's or classes as they are automatically generat ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

Rotation using CSS in Internet Explorer 8

Can anyone help me with a CSS solution for rotating elements in IE8? I've tried some solutions that claim to work in IE8, but they're not working for me. What am I doing wrong? Here's what I've attempted: <!DOCTYPE html> <htm ...

Tips for displaying videos with sound when the autoplay has been successfully implemented, but the audio is not working

I've been working on creating a video player with autoplay functionality, but I'm facing an issue with the sound not playing. Here's what I currently have in my code, but it's not behaving as expected: var myaudio = docum ...

What is the best way to transform arrays like this into a JSON object?

Below is an array that I need to convert into an object: [ [ '560134275538747403', 39953 ], [ '411510958020624384', 36164 ], [ '468512396948930576', 31762 ], [ '482286641982078977', 29434 ], ...

Align the pseudo-element in the center of the parent element using the display property set to table

Can anyone provide guidance on how to center a pseudo-element specifically on an element that utilizes display: table-cell? I have tried various methods but it keeps getting centered only to the parent element with display: table. ...

Arrange two div elements side by side so they remain adjacent even when you adjust the browser size

After years of success with my floated left and right divs, I am now facing a challenge with responsive design. No longer able to rely on fixed widths, I find that when the screen size decreases, the right div moves below the left one. I know that using f ...

Transform the ISO 8601 date format into another ISO 8601 format with the help of MomentJS

Can a date format like the following: 2003-09-25T14:00:00.000+1000 or 2003-09-25T14:00:00.000+1100 Be converted to this format? 2003-09-25T14:00:00.000Z Using only MomentJS without any manual intervention. Additionally, I would like to understa ...

What is the best way to format a date as "2020-01-16 07:29:43.657519000 Z" using JavaScript?

Upon discovering a format 2020-01-16 07:29:43.657519000 Z in a project, I am curious about the significance of the numbers 657519000 and how to replicate this precise format using JavaScript. When attempting new Date().toISOString(), I receive 2020-05-27T2 ...

Leveraging jQuery for handling button functionality and making asynchronous requests

I am relatively new to working with jQuery, and while there are plenty of resources available on how to bind buttons, I find that my current setup is a bit more complex than what's typically covered. My situation involves: -Using Django to populate ...

Is AJAX not submitting properly?

Here is the code snippet that I am working with: var just = $("#just").val(); var id = $("#id").val(); $.ajax({ type: "POST", url: "cod_ajax/just.php", data: "id="+id+"&just="+just, cache: false, success:function(e){ aler ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

Saving multiple instances of an object using Mongoose

In my Mongoose model, I have a blog schema where each blog can have multiple comments attached to it. var mongoose = require('mongoose') , Schema = mongoose.Schema var blogScheam = Schema({ title: String, comments: ...