Bootstrap V5 Alert Dismissing: Asking for confirmation when "Close Button" is clicked

Viewed 264

I'm trying to add a nice confirmation message using Sweetalert2 to the bootstrap version 5 alert component.

how does it work?

when I clicked to "Close Button" (X) it should display a confirmation message with two options (Yes) and (No) if I clicked to (Yes) the alert component should be closed if (No) the alert component should be displayed.

that's it.

the issue that I face is in the close event when I put this code inside it and clicked to (Yes) Option in sweatalert2 confirmation message it shows me an error message in my dev console!

reference: https://getbootstrap.com/docs/5.0/components/alerts/#dismissing

HTML code:

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields below.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

JS code:

if ($(".alert").length) {
    $(".alert").on("close.bs.alert", 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) {
                    var alertNode = document.querySelector(".alert");
                    var alert = bootstrap.Alert.getInstance(alertNode);
                    alert.close();
                }
            });
    });
}
1 Answers

Issues

  1. alert instance was not created. so create it before closing the alert.

  2. off the close.bs.alert event before closing the alert programmatically. It prevents infinite execution.

Note

You can also use jQuery with bootstrap 5. So it can also be simplified as

$(e.target).off('close.bs.alert').alert('close'); 

$(".alert").on("close.bs.alert", 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) {
        // using js
        var alertNode = document.querySelector(".alert");
        var alert = new bootstrap.Alert(alertNode);
        
        $(alertNode).off('close.bs.alert')
        alert.close();

        // using jQuery
        // $(e.target).off('close.bs.alert').alert('close'); 
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>


<div class="alert alert-warning alert-dismissible fade show mt-5" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields below.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

Related