Search code examples
javascriptangularjstimersweetalert2

Sweet Alert, but buttons are disabled for the first few seconds


I am creating a Sweet Alert that displays a very important message, and I don't want the user to dismiss it without reading.

So to emphasize the importance of the message, I would like to make the OK button disabled for (let's say...) 5 seconds, so the user must wait at least that before dismissing the alert.

A visible timer would be sweet too. I am using AngularJS in my application.

I could easily make a custom modal as an alert for this purpose, but the reason I want to use Sweet Alert is because it's already being used all over my application and I don't want to break the pattern.


Solution

  • You can implement this using what's available in SweetAlert2 already. As mentioned in the other answer by Joseph, you should set the following sweetalert2 properties to false to avoid the user to dismiss the modal:

    allowOutsideClick: false,
    allowEscapeKey: false, 
    

    You can then hide the confirm button when the swal is shown:

    onOpen: () => {
      swal.showLoading()
      ....
    }
    

    and then show again the confirm button after some time using a setTimeout:

    onOpen: () => {
      swal.showLoading()
      setTimeout(() => { swal.hideLoading() }, 5000)
    }
    

    The full code of the swal is then:

    swal({
      title: 'Please read this message!',
      allowOutsideClick: false,
      allowEscapeKey: false, 
      onOpen: () => {
        swal.showLoading()
        setTimeout(() => { swal.hideLoading() }, 5000)
      },
    }).then((result) => {
      if (!result.dismiss) {
         console.log('user read the important message')
      }
    })