Search code examples
javascriptjquerybootstrap-modalbootstrap-5

Bootstrap V5 & jQuery: The close event does not return when opened the modal again


I add some special functionality in my modal close event with sweetalert2 but I have faced some issues when I close the modal the first time the close event does not show up again when I opened.

Live Example:

https://codepen.io/themes4all/pen/oNWeYzp

Note:

to know exactly what I'm talking about trying to close the modal and opened and closed again.

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");
                    });
            });
            $(".modal").on("hide.bs.modal", 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) {
                            $(this).off("hide.bs.modal").modal("hide");
                            $(".modal-backdrop").remove();
                            $("body").removeClass("modal-open").removeAttr("style");
                        }
                    });
            });
        }
    });
})(window.jQuery);

Solution

    1. Remove the data-bs-dismiss attribute from the close button.
    2. Instead of calling the method on hide, call the sweetalert on the close button click.
    3. And on confirming the sweetalert, just do $(".modal").modal("hide") This should work.

    JSFiddle