Search code examples
javascriptalertsweetalertsweetalert2

Delay appearance of buttons in sweetalert2


I am using SweetAlert2 to communicate some feedback to the user. This is a learning app, so, I want the feedback to persist for some time. I do not want to show any buttons immediately after the feedback is displayed because people have a tendency to just click on 'OK' or 'Cancel', without reading the text.

The number of characters in the feedback varies from screen to screen, so, I am using the timer parameter of sweetalert2 to be some multiple of the number of characters in the text. But, the timer feature is imperfect because people have different reading speeds. Ideally, I would want the 'OK' button to appear after the timer has timed out. Is there some sort of an API call I can make to dynamically change the property of the alert box?

swal({
        html: feedback,
        timer: feedback.length*50,
        showCloseButton: false,
        showCancelButton: false,
        showConfirmButton: false,
        allowOutsideClick: false,
    });

Solution

  • Hi to achive this you can use a set timeout function and call jQuery's .show() function on the buttons that you wish to show (Assuming you are ok with using jQuery).

    The following code should help you out

    swal({
            html: feedback,
            timer: feedback.length*50,
            showCloseButton: false,
            showCancelButton: false,
            showConfirmButton: false,
            allowOutsideClick: false,
        });
        setTimeout(function () {
            $(".swal2-cancel").show();
            $(".swal2-confirm").show();
            $(".swal2-close").show();
        }, 3000);
    

    Hope this helps :-)