Friday, July 9, 2021

Creating Pretty Popup Messages Using SweetAlert2

Creating Pretty Popup Messages Using SweetAlert2

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:

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

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:

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.

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.

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 completion of a download file, etc.

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.

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:

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.

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
  • 9 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

5. flavr—Flat jQuery Popup Dialog

Let's wrap up this list with flavr. It's a jQuery popup template that uses an incredible, flat design language. Not only is it easy to use, but it's also easy to make look good on multiple screen sizes thanks to the responsive design. If you don't have the time to use CSS for an alert box in JavaScript, try flavr.

flavr Flat jQuery Popup Templateflavr Flat jQuery Popup Templateflavr Flat jQuery Popup Template

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.


No comments:

Post a Comment