SweetAlert2 is a beautiful, customizable, and accessible replacement for JavaScript’s alert()
, confirm()
, and prompt()
boxes. It provides a more visually appealing and user-friendly way to present notifications, confirmations, and prompts to users in web applications. Unlike the default browser dialogs, SweetAlert2 offers extensive customization options for styling, content, and functionality.
SweetAlert2 can be installed via several methods:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@sweetalert2/themes@6/dark/dark.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
npm install sweetalert2
Then, import it into your JavaScript file:
import Swal from 'sweetalert2';
yarn add sweetalert2
Then, import it into your JavaScript file:
import Swal from 'sweetalert2';
After installation, you are ready to use SweetAlert2 in your project.
This example demonstrates a simple success alert:
.fire({
Swalicon: 'success',
title: 'Success!',
text: 'Your action was successful.',
; })
This code will display a SweetAlert2 popup with a green success icon, the title “Success!”, and the text “Your action was successful.” More complex examples with different icons, input fields, and custom HTML are possible through additional options documented in the full API reference.
SweetAlert2 provides several built-in alert types, each with a distinct icon and default styling to convey different messages effectively. These types are easily implemented by setting the icon
parameter in the Swal.fire()
function.
Success alerts indicate a successful operation. They are typically displayed with a green checkmark icon.
.fire({
Swalicon: 'success',
title: 'Success!',
text: 'Your operation was successful.'
; })
Error alerts inform users of an error that occurred. They are usually displayed with a red exclamation mark icon.
.fire({
Swalicon: 'error',
title: 'Oops...',
text: 'Something went wrong!'
; })
Warning alerts caution users about potential issues or actions that require confirmation. They typically use a yellow triangle icon.
.fire({
Swalicon: 'warning',
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!'
; })
Info alerts provide neutral information or updates to the user. They generally display with a blue “i” icon.
.fire({
Swalicon: 'info',
title: 'Information',
text: 'Here\'s some information for you.'
; })
Question alerts prompt the user for confirmation or a decision. While not a distinct icon
type, they are commonly implemented using the warning
icon and showCancelButton
option for a visually clear choice. (Alternatively, a custom icon could also be used).
.fire({
Swalicon: 'question',
title: 'Are you sure?',
text: 'This action cannot be undone.',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'No'
; })
For more granular control over the alert’s visual style, you can use custom icons. This involves providing an image URL or a data URL as the imageUrl
property. The imageWidth
and imageHeight
properties can be used to control the size of the custom icon.
.fire({
Swaltitle: 'Custom Icon!',
imageUrl: 'path/to/your/custom-icon.png',
imageWidth: 100,
imageHeight: 100,
imageAlt: 'Custom icon'
; })
Remember to replace 'path/to/your/custom-icon.png'
with the actual path to your custom icon image. Using a data URL allows you to embed the icon directly into your code.
SweetAlert2 offers a wide range of parameters and options to customize the appearance and behavior of your alerts. These are passed as properties within the object passed to Swal.fire()
.
A string representing the title of the alert.
.fire({
Swaltitle: 'My Alert Title'
; })
A string containing the main text of the alert.
.fire({
Swaltitle: 'My Alert',
text: 'This is the alert text.'
; })
A string specifying the alert’s icon type (‘success’, ‘error’, ‘warning’, ‘info’, ‘question’, or null for no icon).
.fire({
Swalicon: 'warning'
; })
A string to customize the text of the confirmation button.
.fire({
SwalconfirmButtonText: 'Continue'
; })
A string to customize the text of the cancel button (only shown if showCancelButton
is true).
.fire({
SwalshowCancelButton: true,
cancelButtonText: 'Abort'
; })
A boolean indicating whether to display a cancel button (defaults to false).
.fire({
SwalshowCancelButton: true
; })
A boolean controlling whether clicking outside the alert dismisses it (defaults to true).
.fire({
SwalallowOutsideClick: false
; })
A boolean controlling whether pressing the Escape key dismisses the alert (defaults to true).
.fire({
SwalallowEscapeKey: false
; })
A number specifying the time (in milliseconds) before the alert automatically closes.
.fire({
Swaltimer: 2000 // Closes after 2 seconds
; })
A boolean indicating whether to display a progress bar for the timer (defaults to false).
.fire({
Swaltimer: 3000,
timerProgressBar: true
; })
An object or string containing CSS classes to customize the alert’s appearance.
.fire({
SwalcustomClass: {
popup: 'my-custom-popup',
confirmButton: 'my-custom-confirm-button'
}; })
A string specifying the alert’s position (‘top’, ‘top-start’, ‘top-end’, ‘center’, ‘bottom’, ‘bottom-start’, ‘bottom-end’).
.fire({
Swalposition: 'top-end'
; })
A string specifying the background color of the alert.
.fire({
Swalbackground: '#f0f0f0'
; })
A string or number specifying the width of the alert (e.g., ‘500px’, 500).
.fire({
Swalwidth: '300px'
; })
A string specifying the padding of the alert.
.fire({
Swalpadding: '2em'
; })
A string specifying the type of input field to include (‘text’, ‘email’, ‘password’, ‘number’, ‘tel’, ‘select’, ‘radio’, ‘checkbox’, ‘textarea’).
.fire({
Swalinput: 'text'
; })
A function that validates the input value.
.fire({
Swalinput: 'email',
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}if (!/^[^@]+@[^@]+\.[^@]+$/.test(value)) {
return 'Invalid email address'
}
} })
A string representing the placeholder text for the input field.
.fire({
Swalinput: 'text',
inputPlaceholder: 'Enter your name'
; })
A string or number representing the initial value for the input field.
.fire({
Swalinput: 'text',
inputValue: 'Initial Value'
; })
A boolean to show the loading indicator while preConfirm
is executed.
.fire({
SwalshowLoaderOnConfirm: true,
preConfirm: () => {
return new Promise((resolve) => {
setTimeout(() => { resolve() }, 2000);
;
})
}; })
An asynchronous function executed before the alert closes, allowing for validation or asynchronous operations. Its return value will be available in the result object after the alert closes.
.fire({
Swalinput: 'text',
preConfirm: (value) => {
return fetch(`/api/user/${value}`)
.then(response => response.json())
.then(data => data.id);
}.then((result) => {
})console.log(result.value) //The id from the api call
; })
A function executed just before the alert opens.
.fire({
SwalonBeforeOpen: () => {
// Do something before the alert opens
}; })
A function executed after the alert has opened.
.fire({
SwalonOpen: () => {
// Do something after the alert opens
}; })
A function executed after the alert has closed.
.fire({
SwalonClose: () => {
// Do something after the alert closes
}; })
A function executed before the alert closes. Can be used to prevent closing. Return false
from the function to prevent the alert from closing.
.fire({
SwalonBeforeClose: () => {
// Do something before the alert closes. Return false to prevent closing.
return false;
}; })
A function executed after the alert has fully closed and been removed from the DOM.
.fire({
SwalonAfterClose: () => {
// Do something after the alert is fully closed
}; })
A boolean value that controls whether the alert should be closed when the Escape key is pressed (defaults to true
).
.fire({
SwalstopOnEsc: false
; })
A boolean value that controls whether the alert should be closed when the backdrop (the overlay behind the alert) is clicked (defaults to true
).
.fire({
SwalstopOnBackdropClick: false
; })
This section covers more complex usage scenarios and techniques for leveraging SweetAlert2’s capabilities.
SweetAlert2 integrates seamlessly with Ajax requests. You can use the preConfirm
option to make an Ajax call and handle the response before closing the alert. This is useful for situations where you need to perform server-side validation or retrieve data before confirming an action.
.fire({
Swaltitle: 'Are you sure?',
text: 'This action will be performed on the server.',
showLoaderOnConfirm: true,
preConfirm: () => {
return fetch('/api/myaction', { method: 'POST' })
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}return response.json()
}).then(data => {
if (data.success) {
return data.message;
else {
} throw new Error(data.error);
}
}).catch(error => {
.showValidationMessage(`Request failed: ${error}`)
Swal
}),
}allowOutsideClick: () => !Swal.isLoading()
.then((result) => {
})if (result.isConfirmed) {
.fire({
Swalicon: 'success',
title: 'Success!',
text: result.value
;
})
}; })
SweetAlert2 works well with JavaScript Promises. The preConfirm
option can return a Promise, allowing you to perform asynchronous operations and handle their results. The .then()
method on the Swal.fire()
call handles the promise’s resolution or rejection.
.fire({
Swaltitle: 'Loading...',
preConfirm: () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data loaded successfully!');
, 2000);
};
})
}.then((result) => {
}).fire({
Swaltitle: 'Result',
text: result.value
;
}); })
You can chain multiple SweetAlert2 instances together to create a sequence of alerts. The .then()
method of one alert’s promise can trigger the next alert.
.fire({
Swaltitle: 'Alert 1'
.then(() => {
})return Swal.fire({
title: 'Alert 2'
;
}).then(() => {
}).fire({
Swaltitle: 'Alert 3'
;
}); })
SweetAlert2 allows you to inject custom HTML content into the alert using the html
parameter. This is useful for creating more complex and dynamic alerts.
.fire({
Swaltitle: 'Custom HTML!',
html: 'You can use <strong>bold text</strong>, <a href="#">links</a> and much more.'
; })
You can dynamically update the content of a SweetAlert2 alert after it’s been opened. Use the Swal
object’s update()
method to modify properties like title
, html
, text
, etc.
const swal = Swal.fire({
title: 'Initial Title',
html: 'Initial Content'
;
})
setTimeout(() => {
.update({
swaltitle: 'Updated Title',
html: 'Updated Content'
;
}), 2000); }
Ensure your SweetAlert2 alerts are accessible by following these guidelines:
alt
text for any custom icons used.SweetAlert2 provides several ways to customize its appearance to match your application’s design.
SweetAlert2 includes a default theme that offers a clean and modern look. This theme is applied automatically if no custom theme or CSS modifications are made. It’s responsive and adapts to different screen sizes.
SweetAlert2 allows you to use pre-built themes or create your own. While SweetAlert2 itself doesn’t directly include many built-in themes beyond its default, you can find community-created themes or build your own. The approach generally involves creating separate CSS files that override or extend SweetAlert2’s default styles. These themes are typically included via CSS imports.
You can customize SweetAlert2’s appearance by directly modifying its CSS. This offers the most granular control over styling. You can target specific elements using their class names (e.g., .swal2-title
, .swal2-content
, .swal2-button
). Remember to include your custom CSS after the SweetAlert2 CSS file to ensure your styles override the defaults. Be aware of potential conflicts with your application’s existing CSS. Using a CSS preprocessor (like Sass or SCSS) can help to organize your styles.
/* Example: Change the background color of the popup */
.swal2-popup {
background-color: #f0f0f0;
}
/* Example: Change the color of the confirm button */
.swal2-confirm {
background-color: #4CAF50;
color: white;
}
If you’re using Sass or SCSS in your project, you can integrate SweetAlert2’s styling more effectively. You will need to obtain the SweetAlert2 Sass files (often available through a separate package or by compiling the source code) and include them in your Sass build process. This enables you to use Sass variables, mixins, and other features to maintain consistency between your application’s styles and SweetAlert2’s. This approach allows more maintainable and scalable customization compared to directly editing the generated CSS.
The exact implementation details will depend on your project setup (e.g., using a build tool like Webpack or Parcel) and the specific way in which you’ve obtained the SweetAlert2 Sass files. The basic idea involves importing the SweetAlert2 Sass files into your application’s Sass files and then potentially extending or overriding its variables and mixins.
This section provides guidance on resolving common issues encountered when using SweetAlert2.
SweetAlert2 is undefined: This usually means that the SweetAlert2 library hasn’t been correctly included in your project. Double-check that you’ve included the JavaScript file (either via CDN or from your package manager) and that the path is correct. Ensure that the script tag is placed correctly in your HTML (ideally just before the closing </body>
tag).
Unexpected token … in JSON response: This error typically occurs when your preConfirm
function receives an invalid JSON response from an Ajax request. Verify that your server is sending a properly formatted JSON response. Use your browser’s developer tools (Network tab) to inspect the actual response.
Uncaught TypeError: Cannot read properties of undefined: This can happen if you’re attempting to access a property of a result object from Swal.fire().then()
before the promise has resolved or if you’re trying to access a property that doesn’t exist on the Swal
object itself. Check your asynchronous code and ensure you’re handling promises correctly. Carefully review the structure of the result object returned in the .then()
method.
Browser Developer Tools: Use your browser’s developer tools (Console and Network tabs) to inspect any JavaScript errors or network requests. This helps pinpoint the source of the problem.
Console Logging: Strategically use console.log()
statements to track variable values and the flow of execution in your code. This is especially helpful when debugging asynchronous operations or complex logic within preConfirm
or other callback functions.
Simplify Your Code: If you’re facing complex issues, try simplifying your SweetAlert2 code to isolate the problem. Start with a minimal example and gradually add features until you identify the source of the error.
Check for CSS Conflicts: If the alert’s appearance is unexpected, ensure that there are no conflicts between your application’s CSS and SweetAlert2’s styles. Use your browser’s developer tools to inspect the applied CSS rules.
SweetAlert2 generally supports modern browsers. However, extremely outdated browsers might exhibit unexpected behavior. SweetAlert2 aims for broad compatibility, but very old browsers might lack support for the technologies used by SweetAlert2 (like ES modules or specific CSS features). For optimal performance and functionality, it’s recommended to target modern browsers with appropriate polyfills if necessary for legacy support.
While SweetAlert2 is regularly updated, known issues may exist. Check the SweetAlert2 project’s issue tracker or documentation for any reported bugs or workarounds. If you encounter an issue not documented, consider submitting a detailed report to the project maintainers, including steps to reproduce the problem, browser information, and relevant code snippets. Providing a codepen demonstrating the issue is very helpful.
This section provides guidance on migrating from older versions of SweetAlert2 to the latest version. The specific changes will depend on the versions involved. Always consult the official release notes for the most accurate and detailed information.
This section would list significant changes between the previous major version and the current one. This would include, but not be limited to:
Exampl:
date
). Deprecated the confirmButtonColor
parameter; use customClass
instead. Improved accessibility by adding ARIA attributes.This section would detail any changes that might cause your existing code to break when upgrading. This includes, but is not limited to:
Example:
inputAttributes
parameter was removed; use the more flexible inputOptions
parameter instead. The onConfirm
callback is now deprecated; use .then()
instead.This section outlines a step-by-step guide to upgrading your code to the latest version:
package.json
(if using npm or yarn) or replace the CDN links with the latest version.Example (Illustrative - Adapt to specific version):
To upgrade from v10 to v11:
package.json
: npm install sweetalert2@11
inputAttributes
with inputOptions
in your SweetAlert2 calls.onConfirm
with the appropriate logic using the .then()
method.Remember to consult the official release notes and changelog for the most up-to-date and accurate migration instructions.
This section provides a comprehensive reference for the SweetAlert2 API. For the most up-to-date and detailed information, always refer to the official SweetAlert2 documentation. This example provides a simplified overview.
SweetAlert2 primarily uses the Swal.fire()
method to display alerts. However, there are other utility methods available:
Swal.fire(params)
: This is the core method to display a SweetAlert2 popup. params
is an object containing the various configuration options (title, text, icon, etc.). This method returns a Promise that resolves with an object containing information about the user’s interaction (e.g., whether they clicked “OK” or “Cancel”).
Swal.getPopup()
: Returns the DOM element of the currently displayed SweetAlert2 popup. Useful for direct DOM manipulation, though generally discouraged in favor of using the API methods.
Swal.update(params)
: Updates the properties of an already open SweetAlert2 popup. The params
object specifies the properties to change. Useful for dynamic content updates.
Swal.close()
: Closes the currently active SweetAlert2 popup.
Swal.isVisible()
: Returns true
if a SweetAlert2 popup is currently visible; otherwise, returns false
.
Swal.showLoading()
: Displays a loading indicator on an already open SweetAlert2 popup. Useful for indicating that an asynchronous operation is in progress.
Swal.hideLoading()
: Hides the loading indicator on an already open SweetAlert2 popup.
Swal.clickConfirm()
: Programmatically simulates a click on the confirm button.
Swal.clickCancel()
: Programmatically simulates a click on the cancel button.
Example:
.fire({
Swaltitle: 'Are you sure?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!'
.then((result) => {
})if (result.isConfirmed) {
.fire('Deleted!', '', 'success');
Swal
}; })
SweetAlert2 doesn’t expose properties directly on a global Swal
object in the same way it does methods. Instead, the properties are set as parameters within the Swal.fire()
or Swal.update()
calls. These parameters control various aspects of the alert’s appearance and behavior (e.g., title
, text
, icon
, confirmButtonText
, timer
, customClass
, etc.). These parameters are described extensively in other sections of this manual.
SweetAlert2 triggers several events throughout its lifecycle. These events can be handled using the onBeforeOpen
, onOpen
, onClose
, onBeforeClose
, and onAfterClose
parameters (all functions) within the Swal.fire()
call. These functions are called at specific points in the alert’s lifecycle:
onBeforeOpen()
: Called immediately before the alert’s popup is opened.onOpen()
: Called immediately after the alert’s popup is opened and is fully visible.onClose()
: Called immediately before the alert’s popup is closed but still visible.onBeforeClose()
: Called before the alert closes. You can prevent the closing by returning false
from this function.onAfterClose()
: Called after the alert has been completely removed from the DOM.Example:
.fire({
Swaltitle: 'My Alert',
onBeforeOpen: () => {
console.log('Alert about to open');
,
}onClose: () => {
console.log('Alert closing');
}; })
Remember to check the official SweetAlert2 documentation for the most complete and up-to-date API reference. This is a simplified overview, and more nuanced aspects may exist depending on the specific version.