SweetAlert - Documentation

Introduction

What is SweetAlert?

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.

Why use SweetAlert?

Installation and Setup

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.

Basic Usage Example

This example demonstrates a simple success alert:

Swal.fire({
  icon: '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.

Alert Types

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

Success alerts indicate a successful operation. They are typically displayed with a green checkmark icon.

Swal.fire({
  icon: 'success',
  title: 'Success!',
  text: 'Your operation was successful.'
});

Error Alerts

Error alerts inform users of an error that occurred. They are usually displayed with a red exclamation mark icon.

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!'
});

Warning Alerts

Warning alerts caution users about potential issues or actions that require confirmation. They typically use a yellow triangle icon.

Swal.fire({
  icon: 'warning',
  title: 'Are you sure?',
  text: 'You won\'t be able to revert this!',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!'
});

Info Alerts

Info alerts provide neutral information or updates to the user. They generally display with a blue “i” icon.

Swal.fire({
  icon: 'info',
  title: 'Information',
  text: 'Here\'s some information for you.'
});

Question Alerts

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).

Swal.fire({
  icon: 'question',
  title: 'Are you sure?',
  text: 'This action cannot be undone.',
  showCancelButton: true,
  confirmButtonText: 'Yes',
  cancelButtonText: 'No'
});

Custom Icons

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.

Swal.fire({
  title: '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.

Parameters and Options

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().

title

A string representing the title of the alert.

Swal.fire({
  title: 'My Alert Title'
});

text

A string containing the main text of the alert.

Swal.fire({
  title: 'My Alert',
  text: 'This is the alert text.'
});

icon

A string specifying the alert’s icon type (‘success’, ‘error’, ‘warning’, ‘info’, ‘question’, or null for no icon).

Swal.fire({
  icon: 'warning'
});

confirmButtonText

A string to customize the text of the confirmation button.

Swal.fire({
  confirmButtonText: 'Continue'
});

cancelButtonText

A string to customize the text of the cancel button (only shown if showCancelButton is true).

Swal.fire({
  showCancelButton: true,
  cancelButtonText: 'Abort'
});

showCancelButton

A boolean indicating whether to display a cancel button (defaults to false).

Swal.fire({
  showCancelButton: true
});

allowOutsideClick

A boolean controlling whether clicking outside the alert dismisses it (defaults to true).

Swal.fire({
  allowOutsideClick: false
});

allowEscapeKey

A boolean controlling whether pressing the Escape key dismisses the alert (defaults to true).

Swal.fire({
  allowEscapeKey: false
});

timer

A number specifying the time (in milliseconds) before the alert automatically closes.

Swal.fire({
  timer: 2000 // Closes after 2 seconds
});

timerProgressBar

A boolean indicating whether to display a progress bar for the timer (defaults to false).

Swal.fire({
  timer: 3000,
  timerProgressBar: true
});

customClass

An object or string containing CSS classes to customize the alert’s appearance.

Swal.fire({
  customClass: {
    popup: 'my-custom-popup',
    confirmButton: 'my-custom-confirm-button'
  }
});

position

A string specifying the alert’s position (‘top’, ‘top-start’, ‘top-end’, ‘center’, ‘bottom’, ‘bottom-start’, ‘bottom-end’).

Swal.fire({
  position: 'top-end'
});

background

A string specifying the background color of the alert.

Swal.fire({
  background: '#f0f0f0'
});

width

A string or number specifying the width of the alert (e.g., ‘500px’, 500).

Swal.fire({
  width: '300px'
});

padding

A string specifying the padding of the alert.

Swal.fire({
  padding: '2em'
});

input

A string specifying the type of input field to include (‘text’, ‘email’, ‘password’, ‘number’, ‘tel’, ‘select’, ‘radio’, ‘checkbox’, ‘textarea’).

Swal.fire({
  input: 'text'
});

inputValidator

A function that validates the input value.

Swal.fire({
  input: 'email',
  inputValidator: (value) => {
    if (!value) {
      return 'You need to write something!'
    }
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(value)) {
      return 'Invalid email address'
    }
  }
})

inputPlaceholder

A string representing the placeholder text for the input field.

Swal.fire({
  input: 'text',
  inputPlaceholder: 'Enter your name'
});

inputValue

A string or number representing the initial value for the input field.

Swal.fire({
  input: 'text',
  inputValue: 'Initial Value'
});

showLoaderOnConfirm

A boolean to show the loading indicator while preConfirm is executed.

Swal.fire({
  showLoaderOnConfirm: true,
  preConfirm: () => {
    return new Promise((resolve) => {
      setTimeout(() => { resolve() }, 2000);
    });
  }
});

preConfirm

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.

Swal.fire({
  input: '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
});

onBeforeOpen

A function executed just before the alert opens.

Swal.fire({
  onBeforeOpen: () => {
    // Do something before the alert opens
  }
});

onOpen

A function executed after the alert has opened.

Swal.fire({
  onOpen: () => {
    // Do something after the alert opens
  }
});

onClose

A function executed after the alert has closed.

Swal.fire({
  onClose: () => {
    // Do something after the alert closes
  }
});

onBeforeClose

A function executed before the alert closes. Can be used to prevent closing. Return false from the function to prevent the alert from closing.

Swal.fire({
  onBeforeClose: () => {
    // Do something before the alert closes. Return false to prevent closing.
    return false;
  }
});

onAfterClose

A function executed after the alert has fully closed and been removed from the DOM.

Swal.fire({
  onAfterClose: () => {
    // Do something after the alert is fully closed
  }
});

stopOnEsc

A boolean value that controls whether the alert should be closed when the Escape key is pressed (defaults to true).

Swal.fire({
  stopOnEsc: false
});

stopOnBackdropClick

A boolean value that controls whether the alert should be closed when the backdrop (the overlay behind the alert) is clicked (defaults to true).

Swal.fire({
  stopOnBackdropClick: false
});

Advanced Usage

This section covers more complex usage scenarios and techniques for leveraging SweetAlert2’s capabilities.

Ajax Requests

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.

Swal.fire({
  title: '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 => {
        Swal.showValidationMessage(`Request failed: ${error}`)
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire({
      icon: 'success',
      title: 'Success!',
      text: result.value
    });
  }
});

Promises

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.

Swal.fire({
  title: 'Loading...',
  preConfirm: () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('Data loaded successfully!');
      }, 2000);
    });
  }
}).then((result) => {
  Swal.fire({
    title: 'Result',
    text: result.value
  });
});

Chaining Alerts

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.

Swal.fire({
  title: 'Alert 1'
}).then(() => {
  return Swal.fire({
    title: 'Alert 2'
  });
}).then(() => {
  Swal.fire({
    title: 'Alert 3'
  });
});

Custom HTML Content

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.

Swal.fire({
  title: 'Custom HTML!',
  html: 'You can use <strong>bold text</strong>, <a href="#">links</a> and much more.'
});

Dynamic Content Updates

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(() => {
  swal.update({
    title: 'Updated Title',
    html: 'Updated Content'
  });
}, 2000);

Accessibility Considerations

Ensure your SweetAlert2 alerts are accessible by following these guidelines:

Themes and Styling

SweetAlert2 provides several ways to customize its appearance to match your application’s design.

Default Theme

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.

Custom Themes

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.

CSS Customization

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;
}

Sass/SCSS Integration

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.

Troubleshooting

This section provides guidance on resolving common issues encountered when using SweetAlert2.

Common Errors

Debugging Tips

Browser Compatibility

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.

Known Issues

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.

Migration Guide (if applicable)

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.

Changes from previous versions

This section would list significant changes between the previous major version and the current one. This would include, but not be limited to:

Exampl:

Breaking changes

This section would detail any changes that might cause your existing code to break when upgrading. This includes, but is not limited to:

Example:

Upgrade instructions

This section outlines a step-by-step guide to upgrading your code to the latest version:

  1. Check for breaking changes: Review the breaking changes section to identify any potential issues in your code.
  2. Update the library: Update your package.json (if using npm or yarn) or replace the CDN links with the latest version.
  3. Address breaking changes: Modify your code to address any breaking changes, using the suggestions and alternatives provided.
  4. Test thoroughly: After making the changes, thoroughly test your application to ensure everything works as expected.

Example (Illustrative - Adapt to specific version):

To upgrade from v10 to v11:

  1. Update your package.json: npm install sweetalert2@11
  2. Replace inputAttributes with inputOptions in your SweetAlert2 calls.
  3. Replace calls to onConfirm with the appropriate logic using the .then() method.
  4. Retest your application to verify functionality.

Remember to consult the official release notes and changelog for the most up-to-date and accurate migration instructions.

API Reference

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 Methods

SweetAlert2 primarily uses the Swal.fire() method to display alerts. However, there are other utility methods available:

Example:

Swal.fire({
  title: 'Are you sure?',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire('Deleted!', '', 'success');
  }
});

SweetAlert2 Properties

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 Events

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:

Example:

Swal.fire({
  title: '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.