Creating Nice Alerts with sweetAlert

Share this article

When building JavaScript-driven websites we often have the need to provide feedback to our users to let them know if the action they have performed has been successful or not. In the early days of the web, developers used to create messages using the window.alert() function. While alert() works in practice and it’s also consistent across browsers, it’s not very flexible and, to be honest, its look and feel is terrible. Today there are several approaches adopted that range from modals to inline messages. In this article I’ll introduce you to sweetAlert, a library that acts as a replacement for the JavaScript’s alert() function.

What is sweetAlert?

As mentioned in the introduction sweetAlert is a replacement for JavaScript’s window.alert() function that shows very pretty modal windows. It’s a standalone library that has no dependencies, and it’s made from a JavaScript file plus a CSS file. This library comes in three different flavors. The first is a library that you can use in any web project, the second is a fork that is specifically adapted to work with Bootstrap, and the third is a fork that you can use in your Android projects. This project is constantly under work as you can see from the fact that the last version was released just few days ago. Now that you know what this library is all about, let’s see how you can use it in your website.

Getting Started with sweetAlert

To use sweetAlert in your projects you have to download it and include it in the pages where you intend to use this library. There are a few options to download the library: the first is by visiting its GitHub repository, while the second is through Bower. If you choose to use Bower, you have to run the command:
bower install sweetalert
Once downloaded, you can include the JavaScript file with the usual script element as you would do for any other JavaScript library:
<script src="path/to/sweet-alert.min.js"></script>
In addition you must include the CSS file as shown below:
<link rel="stylesheet" href="path/to/sweet-alert.css" />
Once done you’re ready to employ sweetAlert in your website. A minimal example of use is shown below:
sweetAlert('Congratulations!', 'Your message has been successfully sent', 'success');
Resulting in the following output: I don’t know what you’re thinking, but I love the small animation! As you have seen from the previous statement, the library operates through a method called sweetAlert. It accepts up to three parameters:
  • title (mandatory): A string representing the title of the alert shown
  • message (optional): An optional string representing the message shown beneath the title
  • type(optional): An optional string representing the type of message you want to show. Its value may be one of "success", "error", "warning", and "info".
The library also offers a nice shortcut to invoke the sweetAlert method called swal. So, the previous statement can be rewritten as follows:
swal('Congratulations!', 'Your message has been succesfully sent', 'success');
In addition to the parameters presented, the library offers a whole set of options that you can set through an object passed as the first parameter of the method. For example, the previous statement can be rewritten as such:
swal({
   title: 'Congratulations!',
   text: 'Your message has been succesfully sent',
   type: 'success'
});
Now that you know the basics of this library, let’s learn a bit more about its options.

Options

The first option I want to cover allows you to change the text of the buttons shown. For example, if you want to change the text of the button for the success message from “OK” to “Yeah!”, you can set the value for an option called confirmButtonText. If you want to change the text of the button for the cancel button, you have to set the value of cancelButtonText. At this point the most observant of you should raise up the hand and say “I haven’t seen any cancel button so far, what are you talking about?” If you did, excellent! The truth is that sweetAlert allows you to show a cancel message but you have to explicitly specify that you want it. You can do that by setting the option showCancelButton to true
. The following code takes advantage of these three options:
swal({
   title: 'Confirm',
   text: 'Are you sure to delete this message?',
   type: 'warning',
   showCancelButton: true,
   confirmButtonText: 'Yes, sir',
   cancelButtonText: 'Not at all'
});
This code results in the following: In case you don’t like the colors of the confirm button you can also change it by setting a hash value for the confirmButtonColor option. Another interesting option is that you can set that a message is displayed for a fixed amount of time and then is auto-closed. You can achieve this task by passing a number, representing the number of milliseconds after which the message is closed, to an option called timer. The following code uses these other two options:
swal({
   title: 'Confirm',
   text: 'Are you sure to delete this message?',
   type: 'warning',
   showCancelButton: true,
   confirmButtonColor: '#987463',
   timer: 1500
});
It results in the following:

Conclusion

In this article I covered sweetAlert, a library meant as a replacement for JavaScript’s window.alert() function, that allows you to show very nice messages to your users. This library works on any type of device, so you can employ it in your responsive website too. I hope you like the library as much as I do, and that you’ll give it a chance in some of your projects.

Frequently Asked Questions (FAQs) about Creating Nice Alerts with SweetAlert

How Can I Customize the Appearance of My SweetAlert?

SweetAlert allows you to customize the appearance of your alerts to match your website’s theme. You can change the color, font, size, and even the animation of the alert. To do this, you need to pass an object with the desired properties to the SweetAlert function. For example, to change the color and font of the alert, you would use the following code:

swal({
title: "Custom alert!",
text: "This is a custom alert with a different color and font.",
icon: "success",
button: "Aww yiss!",
className: "custom-swal"
});
Then, in your CSS file, you would define the .custom-swal class like this:

.custom-swal {
background-color: #f6f7f9;
font-family: 'Comic Sans MS', cursive, sans-serif;
}

Can I Use HTML in SweetAlerts?

Yes, SweetAlert allows you to use HTML in your alerts. This can be useful if you want to include links, images, or other HTML elements in your alert. To use HTML in a SweetAlert, you need to set the html parameter to true and then include your HTML in the text parameter. Here’s an example:

swal({
title: "HTML alert!",
text: "<strong>This is a bold text.</strong><br><a href='https://www.example.com'>This is a link</a>",
icon: "info",
button: "Got it!",
html: true
});

How Can I Add Buttons to My SweetAlert?

SweetAlert allows you to add one or more buttons to your alerts. These buttons can be used to allow the user to confirm or cancel the action that triggered the alert. To add buttons to a SweetAlert, you need to use the buttons parameter. This parameter takes an array of strings, where each string is the text for a button. Here’s an example:

swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: ["Cancel", "Delete"],
dangerMode: true,
});

In this example, the alert will have two buttons: “Cancel” and “Delete”. The “Delete” button is styled differently because the dangerMode parameter is set to true.

Can I Use SweetAlert with AJAX?

Yes, you can use SweetAlert with AJAX to display alerts based on the result of an AJAX request. This can be useful if you want to display a success message after a successful AJAX request, or an error message if the request fails. To do this, you would use the then method of the SweetAlert function to handle the promise that is returned by the AJAX request. Here’s an example:

swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: '/delete-file',
type: 'POST',
data: {fileId: '123'},
success: function() {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
},
error: function() {
swal("Oops! Something went wrong!", {
icon: "error",
});
}
});
} else {
swal("Your imaginary file is safe!");
}
});

In this example, if the user clicks the “Delete” button, an AJAX request is made to delete a file. If the request is successful, a success alert is displayed. If the request fails, an error alert is displayed.

How Can I Use SweetAlert in a Form?

You can use SweetAlert in a form to display a confirmation message before the form is submitted. This can be useful if you want to give the user a chance to review their input before it is sent to the server. To do this, you would use the preventDefault method of the event object to prevent the form from being submitted, and then use the then method of the SweetAlert function to submit the form if the user confirms. Here’s an example:

$('form').on('submit', function(e) {
e.preventDefault();

swal({
title: "Are you sure?",
text: "Once submitted, you will not be able to change your input!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willSubmit) => {
if (willSubmit) {
this.submit();
} else {
swal("Your input is safe!");
}
});
});

In this example, if the user clicks the “Submit” button, a confirmation alert is displayed. If the user confirms, the form is submitted. If the user cancels, a relief alert is displayed.

How Can I Display a Loading Spinner in SweetAlert?

SweetAlert allows you to display a loading spinner in your alerts. This can be useful if you want to indicate that a process is running in the background and the user needs to wait. To display a loading spinner, you need to use the button parameter with a false value and the closeOnClickOutside parameter with a false value as well. Here’s an example:

swal({
title: "Loading...",
text: "Please wait while we process your request.",
icon: "info",
button: false,
closeOnClickOutside: false,
});

In this example, the alert will display a “Loading…” message and a loading spinner. The user will not be able to close the alert by clicking outside of it.

How Can I Close a SweetAlert Programmatically?

You can close a SweetAlert programmatically by calling the swal.close() method. This can be useful if you want to close the alert after a certain condition is met, or after a certain amount of time has passed. Here’s an example:

swal({
title: "This alert will close in 5 seconds!",
icon: "info",
button: false,
timer: 5000,
});

In this example, the alert will close automatically after 5 seconds.

How Can I Use SweetAlert with Promises?

SweetAlert supports promises, which means you can use it in combination with async/await to handle user input in a more readable and maintainable way. Here’s an example:

async function deleteFile() {
const willDelete = await swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
});

if (willDelete) {
// Delete the file...
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
}

In this example, the swal function returns a promise that resolves to the value of the button that the user clicked. This value is then used to determine whether to delete the file or not.

How Can I Use SweetAlert with React?

SweetAlert has a React version called react-sweetalert. This version allows you to use SweetAlert in your React applications in a more idiomatic way. Here’s an example:

import React from 'react';
import SweetAlert from 'react-sweetalert';

class MyApp extends React.Component {
state = {
alert: null
};

showAlert = () => {
this.setState({
alert: (
<SweetAlert
title="Are you sure?"
text="Once deleted, you will not be able to recover this imaginary file!"
showCancelButton
onConfirm={this.deleteFile}
onCancel={this.hideAlert}
/>
)
});
};

hideAlert = () => {
this.setState({
alert: null
});
};

deleteFile = () => {
// Delete the file...
this.hideAlert();
};

render() {
return (
<div>
<button onClick={this.showAlert}>Delete file</button>
{this.state.alert}
</div>
);
}
}

export default MyApp;

In this example, the SweetAlert component is rendered conditionally based on the state of the MyApp component. The onConfirm and onCancel props are used to handle the user’s input.

How Can I Use SweetAlert with Vue.js?

SweetAlert has a Vue.js version called vue-sweetalert2. This version allows you to use SweetAlert in your Vue.js applications in a more idiomatic way. Here’s an example:

<template>
<button @click="showAlert">Delete file</button>
</template>

<script>
import Vue from 'vue';
import VueSweetalert2 from 'vue-sweetalert2';

Vue.use(VueSweetalert2);

export default {
methods: {
showAlert() {
this.$swal({
title: 'Are you sure?',
text: 'Once deleted, you will not be able to recover this imaginary file!',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, keep it'
}).then((result) => {
if (result.value) {
// Delete the file...
this.$swal('Deleted!', 'Your file has been deleted.', 'success');
} else if (result.dismiss === 'cancel') {
this.$swal('Cancelled', 'Your imaginary file is safe :)', 'error');
}
});
}
}
};
</script>

In this example, the $swal method is used to display the alert. The then method is used to handle the user’s input.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

ColinI
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week