Antoine Hedin
Information systems - Java and Web technologies

SweetAlert: stylized alternative to javascript alert popups
Published on 30/11/2014 - Updated on 29/05/2016

Presentation

SweetAlert is a Javascript library designed by Tristan Edwards. Easy to understand and use, it is valuable to show to users of an application or a website some alerts that are much more pleasant and ergonomic than their standard equivalents.

 

Overview

A basic example of how an error alert can be displayed:

 

 

The confirmation of an action can also be enhanced:

 

 

In this more complete example, the image associated to the confirmation message has been customized. Moreover, cancellation and confirmation buttons lead up to complementary alerts.

 

References

Javascript and CSS files composing this library as well as its documentation (settings, options, customization) are available on GitHub: https://github.com/t4t5/sweetalert.

 

Implementation

First of all, declare the library's CSS and javascript files in the page header:

<link rel="stylesheet" type="text/css" href="path/sweet-alert.css" />
<script type="text/javascript" src="path/sweet-alert.min.js"></script>

An identifier or a class can hence be assigned to a button or any other element responsible of triggering the alert:

<button id="myButton" class="myButton">My button</button>

Finally associate the SweetAlert initialization function to the triggering element when the page is being loaded. The code example below consists in an initialization through jQuery of a button by its identifier and produces the result of the second example shown above in this article:

<script type="text/javascript">
  $(document).ready(function() {
    $("#myButton").click(function() {
      swal(
        {
          title: "Are you sure?",
          text: "Do you really want to execute this dummy action?",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "Yes, I do!",
          allowOutsideClick: true,
          imageUrl: "http://www.antoinehedin.com/silverpeas/anthed/img/logo.png",
          closeOnConfirm: false,
          closeOnCancel: false
        },
        function(isConfirm) {
          if (isConfirm) {
            swal("Action confirmed", "Dummy action has been executed.", "success");
          } else {
            swal("Action cancelled", "Nothing happened", "error");
          }
        }
      );
    });
  });
</script>

The settings is self-explanatory and customization of the content and display can of course be enlarged by overriding the basic stylesheet.