Advertisement
  1. Code
  2. JavaScript

Creating Pretty Popup Messages Using SweetAlert2

Scroll to top

Every now and then, you'll have to show an alert box to your users to let them know about an error or notification. The problem with the default alert boxes provided by browsers is that they're not very attractive. When you're creating a website with great color combinations and fancy animation to improve the browsing experience of your users, the unstyled alert boxes will seem out of place.

In this tutorial, you'll learn about a library called SweetAlert2, which allows us to create all kinds of alert messages that can be customized to match the look and feel of our own website.

Display Simple Alert Messages

Before you can show all those sweet alert messages to your users, you'll have to install the library and include it in your project. If you're using npm or bower, you can install it by running the following commands:

1
npm install sweetalert2
2
bower install sweetalert2

You can also get a CDN link for the latest version of the library and include it in your webpage using script tags:

1
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.10.1/dist/sweetalert2.all.min.js"></script>

Besides the JavaScript file, you'll also have to load a CSS file which is used to style all the alert boxes created by the library:

1
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/sweetalert2@10.10.1/dist/sweetalert2.min.css'>

Once you've installed the library, creating a sweet alert is actually very easy. All you have to do is call the Swal.fire() function. Just make sure that the function is called after the DOM has loaded.

There are two ways to create a sweet alert using the Swal.fire() function. You can either pass the title, body text, and icon value in three different arguments, or you can pass a single argument as an object with different values as its key-value pairs. Passing everything in an object is useful when you want to specify values for multiple arguments.

Note: older versions of SweetAlert2 use a swal() function instead of Swal.fire(). If you try to use the old swal() function, you'll get the error "Cannot call a class as a function".

When a single argument is passed and it's a string, the sweet alert will only show a title and an OK button. Users will be able to click anywhere outside the alert or on the OK button in order to dismiss it.

When two arguments are passed, the first one becomes the title and the second one becomes the text inside the alert. You can also show an icon in the alert box by passing a third argument. This can have any of the five predefined values: warningerrorsuccessinfo, and question. If you don't pass the third argument, no icon will be shown inside the alert message.

1
document.querySelector(".first").addEventListener('click', function(){
2
  Swal.fire("Our First Alert");
3
});
4
5
document.querySelector(".second").addEventListener('click', function(){
6
  Swal.fire("Our First Alert", "With some body text!");
7
});
8
9
document.querySelector(".third").addEventListener('click', function(){
10
  Swal.fire("Our First Alert", "With some body text and success icon!", "success");
11
});

Configuration Options to Customize Alerts

If you simply want to show some basic information inside an alert box, the previous example will do just fine. However, the library can actually do a lot more than just showing users some text inside an alert message. You can change every aspect of these alert messages to suit your own needs.

We have already covered the title, the text, and the icons inside a sweet alert message. There is also an option to change the buttons inside it and control their behavior. By default, an alert will only have a single confirm button with text that says "OK". You can change the text inside the confirm button by setting the value of the confirmButtonText property. If you also want to show a cancel button in your alert messages, all you have to do is set the value of showCancelButton to true. The text inside the cancel button can be changed using the cancelButtonText property.

Each of these buttons can be given a different background color using the confirmButtonColor and cancelButtonColor properties. The default color for the confirm button is #3085d6, while the default color for the cancel button is #aaa. If you want to apply any other customization on the confirm or cancel buttons, you can simply use the confirmButtonClass and cancelButtonClass properties to add a new class to them. Once the classes have been added, you'll be able to use CSS to change the appearance of those buttons. You can also add a class on the main modal itself by using the customClass property.

If you interacted with the alert messages in the first example, you might have noticed that the modals can be closed by pressing either the Enter or Escape key. Similarly, you can also click anywhere outside the modal in order to dismiss it. This happens because the value of allowEnterKeyallowEscapeKey, and allowOutsideClick is set to true by default.

When you show two different buttons inside a modal, the confirm button is the one which is in focus by default. You can remove the focus from the confirm button by setting the value of focusConfirm to false. Similarly, you can also set the focus on the cancel button by setting the value of focusCancel to true.

The confirm button is always shown on the left side by default. You have the option to reverse the positions of the confirm and cancel buttons by setting the value of reverseButtons to true.

Besides changing the position and color of buttons inside the alert messages, you can also change the background and position of the alert message or the backdrop around it. Not only that, but the library also allows you to show your own custom icons or images in the alert messages. This can be helpful in a lot of situations.

You can customize the backdrop of a sweet alert using the backdrop property. This property accepts either a Boolean or a string as its value. By default, the backdrop of an alert message consists of mostly a transparent gray color. You can hide it completely by setting the value of backdrop to false. Similarly, you can also show your own images in the background by setting the backdrop value as a string. In such cases, the whole value of the backdrop string is assigned to the CSS background property. The background of a sweet alert message can be controlled using the background property. All alert messages have a completely white background by default.

All the alert messages pop up at the center of the window by default. However, you can make them pop up from a different location using the position property. This property can have nine different values with self-explanatory names: toptop-starttop-endcentercenter-startcenter-endbottombottom-start, and bottom-end.

You can disable the animation when a modal pops up by setting the value of the animation property to false. The library also provides a timer property which can be used to auto-close the timer once a specific number of milliseconds have passed.

In the following example, I have used different combinations of all the properties discussed in this section to create four different alert messages. This should demonstrate how you can completely change the appearance and behavior of a modal created by the SweetAlert2 library.

1
document.querySelector(".first").addEventListener("click", function() {
2
  Swal.fire({
3
    title: "Show Two Buttons Inside the Alert",
4
    showCancelButton: true,
5
    confirmButtonText: "Confirm",
6
    confirmButtonColor: "#00ff99",
7
    cancelButtonColor: "#ff0099"
8
  });
9
});
10
11
document.querySelector(".second").addEventListener("click", function() {
12
  Swal.fire({
13
    title: "Are you sure about deleting this file?",
14
    type: "info",
15
    showCancelButton: true,
16
    confirmButtonText: "Delete It",
17
    confirmButtonColor: "#ff0055",
18
    cancelButtonColor: "#999999",
19
    reverseButtons: true,
20
    focusConfirm: false,
21
    focusCancel: true
22
  });
23
});
24
25
document.querySelector(".third").addEventListener("click", function() {
26
  Swal.fire({
27
    title: "Profile Picture",
28
    text: "Do you want to make the above image your profile picture?",
29
    imageUrl: "https://images3.imgbox.com/4f/e6/wOhuryw6_o.jpg",
30
    imageWidth: 550,
31
    imageHeight: 225,
32
    imageAlt: "Eagle Image",
33
    showCancelButton: true,
34
    confirmButtonText: "Yes",
35
    cancelButtonText: "No",
36
    confirmButtonColor: "#00ff55",
37
    cancelButtonColor: "#999999",
38
    reverseButtons: true,
39
  });
40
});
41
42
document.querySelector(".fourth").addEventListener("click", function() {
43
  Swal.fire({
44
    title: "Alert Set on Timer",
45
    text: "This alert will disappear after 3 seconds.",
46
    position: "bottom",
47
    backdrop: "linear-gradient(yellow, orange)",
48
    background: "white",
49
    allowOutsideClick: false,
50
    allowEscapeKey: false,
51
    allowEnterKey: false,
52
    showConfirmButton: false,
53
    showCancelButton: false,
54
    timer: 3000
55
  });
56
});

Creating Toasts With SweetAlert2

You have probably seen small messages or alerts that appear on smartphones every now and then. These messages appear near the bottom of the screen over all other content and disappear after some time. They're useful when you want to inform users about something like the completion of a file download.

You can turn any alert into a toast notification by setting the value of the toast parameter to true. Toasts will show up in the middle of the screen if you don't specify a position with the position parameter because position defaults to center when left unspecified.

1
Swal.fire({
2
    toast: true,
3
    icon: 'success',
4
    title: 'Posted successfully',
5
    animation: false,
6
    position: 'bottom',
7
    showConfirmButton: false,
8
    timer: 3000,
9
    timerProgressBar: true,
10
    didOpen: (toast) => {
11
      toast.addEventListener('mouseenter', Swal.stopTimer)
12
      toast.addEventListener('mouseleave', Swal.resumeTimer)
13
    }
14
  })

A lot of alerts and toasts that you add to your website will probably use the same value of attributes for consistency. For example, let's say you want to create two separate toasts: one for successful sign-in and another for the wrong password. You can use the mixin() method to avoid any duplication. This method returns an extended version of Swal that consists of all the supplied parameters as default values. You no longer need to supply the same values again and again to different alerts.

Here is an example:

1
var toastMixin = Swal.mixin({
2
    toast: true,
3
    icon: 'success',
4
    title: 'General Title',
5
    animation: false,
6
    position: 'top-right',
7
    showConfirmButton: false,
8
    timer: 3000,
9
    timerProgressBar: true,
10
    didOpen: (toast) => {
11
      toast.addEventListener('mouseenter', Swal.stopTimer)
12
      toast.addEventListener('mouseleave', Swal.resumeTimer)
13
    }
14
  });
15
  
16
document.querySelector(".second").addEventListener('click', function(){
17
  toastMixin.fire({
18
    animation: true,
19
    title: 'Signed in Successfully'
20
  });
21
});
22
23
document.querySelector(".third").addEventListener('click', function(){
24
  toastMixin.fire({
25
    title: 'Wrong Password',
26
    icon: 'error'
27
  });
28
});

Storing the mixin in a variable allows us to call fire() at a later point, with parameters that either specify a new value or override the default values. The following CodePen demo shows all three toasts in action.

Important SweetAlert2 Methods

Initializing different sweet alert messages to show them to users is one thing, but sometimes you'll also need access to methods which control the behavior of those alert messages after initialization. Fortunately, the SweetAlert2 library provides many methods that can be used to show or hide a modal as well as getting its title, text, image, etc.

You can check if a modal is visible or hidden using the isVisible() method. You can also programmatically close an open modal by using the close() or closeModal() methods.

If you happen to use the same set of properties for multiple alert messages during their initialization, you can simply create a new Sweet Alert instance with Swal.mixin(). Pass a configuration object, and Swal.mixin() will return a new instance with those configurations pre-set.

1
const Toast = Swal.mixin({
2
  toast: true,
3
  position: 'top-end',
4
  showConfirmButton: false,
5
})
6
7
//now we can use Toast just like the Swal class

8
Toast.fire(...)

Note that this functionality was provided by the setDefaults() and resetDefaults() methods in Sweet Alert 7.x and earlier.

You can get the title, content, and image of a modal using the getTitle()getContent(), and getImage() methods. Similarly, you can also get the SweetAlert HTML code that makes up the confirm and cancel buttons using the getConfirmButton() and getCancelButton() methods.

There are a number of other methods which can be used to perform other tasks like programmatically clicking on the confirm or cancel buttons.

Pretty Popup JavaScript Templates From CodeCanyon

Working with SweetAlert in PHP is a great way to pick up some new skills. But if you want to get pretty popups without diving too deep into the code, then check out these downloads from CodeCanyon:

1. Kreatura Slider Plugin for jQuery

Kreatura is more than just a jQuery slider plugin. It offers some pretty popups too. It comes with a host of templates that you can use as-is or customize. Thankfully, customization with Kreatura is an easy process. You won't need to spend as much time as you'd have had you made a SweetAlert PHP popup from scratch.

Kreatura Slider and Popup Plugin for jQueryKreatura Slider and Popup Plugin for jQueryKreatura Slider and Popup Plugin for jQuery

2. Slick Modal: CSS3 Powered Popups

Create near-unlimited combinations with Slick Modal. It includes a variety of settings, plugins, and demo templates that make customization a rich experience. Slick Modal will give you features like:

  • content load via Ajax
  • page background effects
  • nine popup positions
  • animated popup, overlay, and content
Slick Modal Pretty Popup Template CSS3 jQuerySlick Modal Pretty Popup Template CSS3 jQuerySlick Modal Pretty Popup Template CSS3 jQuery

3. jQuery Flying Popup

You can create cool popups with this ready-to-use download. jQuery Flying Popup comes with four templates that you can customize for your needs. Its most recent update also added a responsive design, so your popups can fit multiple screen sizes. This is a nice alternative to building a SweetAlert 2 alert from scratch.

jQuery Flying Pretty PopupjQuery Flying Pretty PopupjQuery Flying Pretty Popup

4. jQuery MsgBox

Here's a simple, easy-to-customize script for making popup message boxes. It features minimal popups that are relatively bare-bones. Despite its simplicity, it's a great replacement for the basic functionality of alert(), confirm(), and prompt() functions.

jQuery Msgbox Popup DownloadjQuery Msgbox Popup DownloadjQuery Msgbox Popup Download

Final Thoughts

The SweetAlert2 library makes it very easy for developers to create custom alert messages to show to their users by simply setting the values of a few properties. This tutorial was aimed at covering the basics of this library so that you can create your own custom alert messages quickly.

To prevent the post from getting too big, I have only covered the most commonly used methods and properties. If you want to read about all the other methods and properties which can be used to create advanced alert messages, you should go through the detailed documentation of the library.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.