How to add close button in SweetAlert pop up

Abdul Manaf picture Abdul Manaf · Sep 27, 2017 · Viewed 17.2k times · Source

I have used the SweetAlert library for displaying a pop up in my application. This is my code

swal({
    title: "Are you sure?",
    text: "Test message?",
    type: "info",
    showCancelButton: true,
    focusConfirm: false,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes",
    cancelButtonText: "No"
}, function (isConfirm) {})

I need to add a close button in top right corner. Based on documentation, the close button available only for the SweetAlert2 library.

Is it possible to add close button in the SweetAlert1 library?

Answer

aaron picture aaron · May 4, 2018

You can define a mySwal wrapper that checks for a showCloseButton param.

Here's an example for v2.1.0 of the original SweetAlert library:

mySwal = function() {
  swal(arguments[0]);
  if (arguments[0].showCloseButton) {
    closeButton = document.createElement('button');
    closeButton.className = 'swal2-close';
    closeButton.onclick = function() { swal.close(); };
    closeButton.textContent = '×';
    modal = document.querySelector('.swal-modal');
    modal.appendChild(closeButton);
  }
}

mySwal({
  title: "Are you sure?",
  text: "Test message?",
  icon: "info", /* type: "info", */
  buttons: [
    "No", /* showCancelButton: true, cancelButtonText: "No", */
    "Yes" /* confirmButtonText: "Yes", */
  ],
  focusConfirm: false,
  showCloseButton: true
});
.swal-button--confirm {
  background-color: #dd6b55; /* confirmButtonColor: "#DD6B55", */
}

.swal-modal .swal2-close {
  position: absolute;
  top: 0;
  right: 0;
  width: 1.2em;
  height: 1.2em;
  transition: color 0.1s ease-out;
  border: none;
  background: transparent;
  color: #cccccc;
  font-family: serif;
  font-size: 40px;
  cursor: pointer;
}

.swal-modal .swal2-close:hover {
  color: #f27474;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>