Creating Nice Alerts with sweetAlert — SitePoint (2024)

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.

Creating Nice Alerts with sweetAlert — SitePoint (2024)

FAQs

What are the different types of sweet alerts? ›

SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal.

How do you implement Sweet Alert? ›

Once the library is set up, creating a SweetAlert message is very easy. All you have to do is call the swal() function. swal("Here's a message!", " Have a nice day!")

What is Swal in JavaScript? ›

Sweet JS Provides easy methods to design and add a lot of functionality to the alert box of the website by just calling the function of sweet alert (in short SWAL()).

How to change title of alert box in JavaScript? ›

We can't directly modify the title of the alert box because the title is controlled by the browser and cannot be changed by JavaScript. However, we can create a custom alert box.

What is better than Sweet Alert? ›

JavaScript, Git, GitHub, Python, and jQuery are the most popular alternatives and competitors to SweetAlert. Powerful collaboration, review, and code management for open ... Powerful collaboration, review, and code management for open ...

What are the types of icons in SweetAlert2? ›

SweetAlert2 comes with 5 built-in types which will show a corresponding icon animation: warning, error, success, info and question. It can either be put in the array under the key "type" or passed as the third parameter of the function.

Is SweetAlert2 free? ›

sweetalert2 - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers.

How would you write hello in an alert box? ›

message = "Hello World"; alertBox.

What is the difference between Sweetalert and SweetAlert2? ›

SweetAlert2 is simply a cleaner version. The functions are much easier to use and the documentation provides much more usability, when compared to it's first version. Upon going through the sweetalert upgrade logs, it is recommended to use sweetalert2 because of its easy to use, flexible, awesome new changes.

How do I add an icon in Sweet Alert? ›

The icon of the popup. SweetAlert2 comes with 5 built-in icon which will show a corresponding icon animation: warning, error, success, info, and question. It can either be put in the array under the key "icon" or passed as the third parameter of the function.

How to trigger a JavaScript alert? ›

To use the alert function in JavaScript, you need to call it followed by parentheses and pass a message as a parameter inside the parentheses. The message will be displayed as a popup alert box on the user's screen. alert("Hello, World!"); // Displays a popup with the message "Hello, World!"

What is the alternative to alert box in JavaScript? ›

blurt is a javascript replacement for default alert(), prompt(), and confirm() functions in javascript. The equivalents in blurt are: alert() -> blurt() prompt() -> brompt()

How to create a custom alert in JavaScript? ›

To create an alert in JavaScript, you can use the alert() method. alert("Hello, world!"); When you run the above code, you'll see a pop-up alert box that says "Hello, world!". You can change the message inside the parentheses to display whatever message you want to alert the user with.

Can we style alert box in JavaScript? ›

style. display = “block”; for showing the alert box and when the close button is clicked set the alertBox. style. display = “none”; to hide it.

How to use sweet alert on button click? ›

SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". It can either be put in the array under the key "type" or passed as the third parameter of the function. If set to true, the user can dismiss the modal by pressing the Escape key.

How to import sweet alert in JavaScript? ›

Using React

Note that you need to have both sweetalert and @sweetalert/with-react as dependencies in your package.json . After that, it's easy. Whenever you want to use JSX in your SweetAlert modal, simply import swal from @sweetalert/with-react instead of from sweetalert . This is now rendered with JSX!

How to Sweetalert2? ›

SweetAlert2
  1. Add this script in the header of your layout page: ...
  2. Create a new javascript file in the file manager, for example a “sweetalert2.js” file. ...
  3. Link this file in the end of your layout page's body. ...
  4. Add the following basic code in the newly created sweetalert2.js file. ...
  5. Configuration.
Mar 28, 2022

Top Articles
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6323

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.