Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add close button in SweetAlert pop up

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?

like image 853
Abdul Manaf Avatar asked Dec 07 '22 16:12

Abdul Manaf


2 Answers

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

Just add showCloseButton: true and this will show the close X icon in the top right corner of the pop up.

Source: See the "Custom HTML description and buttons with ARIA labels" example on SweetAlerts2 Docs

Note it is not available in SweetAlert1 library which is now deprecated, I would suggest using SweetAlert2.

like image 150
Andrew Heinke Avatar answered Dec 10 '22 05:12

Andrew Heinke


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>
like image 20
aaron Avatar answered Dec 10 '22 07:12

aaron