Convert Figma logo to code with AI

t4t5 logosweetalert

A beautiful replacement for JavaScript's "alert"

22,400
2,841
22,400
197

Top Related Projects

✨ A beautiful, responsive, highly customizable and accessible (WAI-ARIA) replacement for JavaScript's popup boxes. Zero dependencies. πŸ‡ΊπŸ‡¦

1,553

⚑ 2kB vanilla modal plugin, no dependencies and easy-to-use

3,651

Beautiful JavaScript notifications with Web Notifications support.

Quick Overview

SweetAlert is a beautiful, responsive, customizable, and accessible replacement for JavaScript's popup boxes. It provides a modern and user-friendly way to display alerts, confirmations, and prompts in web applications, enhancing the overall user experience.

Pros

  • Easy to use and integrate into existing projects
  • Highly customizable with a wide range of options and themes
  • Responsive design that works well on both desktop and mobile devices
  • Accessible, with support for keyboard navigation and screen readers

Cons

  • Adds additional weight to the project, which may impact load times
  • Some users might prefer native browser dialogs for consistency
  • Limited built-in animations compared to some other alert libraries
  • Requires JavaScript to function, which may not be ideal for all use cases

Code Examples

  1. Basic alert:
Swal.fire('Hello world!');
  1. Confirmation dialog with custom buttons:
Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})
  1. Input prompt with validation:
Swal.fire({
  title: 'Submit your GitHub username',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Look up',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`//api.github.com/users/${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire({
      title: `${result.value.login}'s avatar`,
      imageUrl: result.value.avatar_url
    })
  }
})

Getting Started

  1. Install SweetAlert:
npm install sweetalert2
  1. Import and use in your JavaScript file:
import Swal from 'sweetalert2'

// Use SweetAlert
Swal.fire('Hello World!');
  1. For usage without a module bundler, include the following in your HTML:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Then you can use SweetAlert in your JavaScript code as shown in the examples above.

Competitor Comparisons

✨ A beautiful, responsive, highly customizable and accessible (WAI-ARIA) replacement for JavaScript's popup boxes. Zero dependencies. πŸ‡ΊπŸ‡¦

Pros of SweetAlert2

  • More actively maintained with frequent updates and bug fixes
  • Offers more customization options and features
  • Better TypeScript support and type definitions

Cons of SweetAlert2

  • Slightly larger file size due to additional features
  • May have a steeper learning curve for beginners
  • Some legacy projects might face compatibility issues when upgrading

Code Comparison

SweetAlert:

swal("Hello world!");

SweetAlert2:

Swal.fire('Hello world!');

Both libraries offer similar basic usage, but SweetAlert2 provides more advanced options:

Swal.fire({
  title: 'Custom width, padding, background.',
  width: 600,
  padding: '3em',
  background: '#fff url(/images/trees.png)',
  backdrop: `rgba(0,0,123,0.4) url("/images/nyan-cat.gif") center top no-repeat`
});

SweetAlert2 also supports chaining for more complex interactions:

Swal.fire('Question 1')
  .then(() => Swal.fire('Question 2'))
  .then(() => Swal.fire('Question 3'));

Overall, SweetAlert2 offers more features and flexibility, making it suitable for complex projects, while the original SweetAlert remains a simpler option for basic alert needs.

1,553

⚑ 2kB vanilla modal plugin, no dependencies and easy-to-use

Pros of Tingle

  • Lightweight and dependency-free, resulting in a smaller footprint
  • More customizable with CSS variables for easy styling
  • Supports multiple instances and callbacks for various modal events

Cons of Tingle

  • Less visually polished out-of-the-box compared to SweetAlert
  • Fewer pre-built modal types and configurations
  • Less extensive documentation and community support

Code Comparison

SweetAlert:

swal({
  title: "Are you sure?",
  text: "You will not be able to recover this file!",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, delete it!",
  closeOnConfirm: false
});

Tingle:

var modal = new tingle.modal({
  footer: true,
  stickyFooter: false,
  closeMethods: ['overlay', 'button', 'escape'],
  closeLabel: "Close",
  cssClass: ['custom-class-1', 'custom-class-2']
});
modal.setContent('<h1>Are you sure?</h1><p>You will not be able to recover this file!</p>');
modal.addFooterBtn('Yes, delete it!', 'tingle-btn tingle-btn--danger', function() {
  // Delete action
});
modal.open();

Both libraries offer easy-to-use modal creation, but SweetAlert provides more pre-configured options, while Tingle offers greater flexibility in terms of content and styling. SweetAlert's API is more concise for common use cases, whereas Tingle requires more manual setup but allows for more complex modal structures.

3,651

Beautiful JavaScript notifications with Web Notifications support.

Pros of PNotify

  • More customizable and feature-rich, offering a wider range of notification types and options
  • Better support for stacking and positioning multiple notifications
  • Includes modules for desktop notifications and mobile-specific styling

Cons of PNotify

  • Larger file size and potentially higher performance overhead
  • Steeper learning curve due to more complex API and configuration options
  • Less visually appealing out-of-the-box compared to SweetAlert's modern design

Code Comparison

SweetAlert:

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

PNotify:

PNotify.notice({
  title: 'Confirmation',
  text: 'Are you sure you want to delete this?',
  icon: 'fas fa-question-circle',
  hide: false,
  modules: {
    Confirm: {
      confirm: true,
      buttons: [{
        text: 'Yes',
        primary: true,
        click: function(notice) {
          notice.close();
          // Perform delete action
        }
      }]
    }
  }
});

The code comparison shows that PNotify requires more configuration for a similar confirmation dialog, but offers greater flexibility in customization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

SweetAlert

A beautiful replacement for JavaScript's "alert"

npm version Build status

A success modal

Installation

$ npm install --save sweetalert

Usage

import swal from 'sweetalert';

swal("Hello world!");

Upgrading from 1.X

Many improvements and breaking changes have been introduced in the 2.0 release. Make sure you read the upgrade guide to avoid nasty surprises!

Guides

Documentation

Examples

An error message:

swal("Oops!", "Something went wrong!", "error");

A warning message, with a function attached to the confirm message:

  • Using promises:
swal({
  title: "Are you sure?",
  text: "Are you sure that you want to leave this page?",
  icon: "warning",
  dangerMode: true,
})
.then(willDelete => {
  if (willDelete) {
    swal("Deleted!", "Your imaginary file has been deleted!", "success");
  }
});
  • Using async/await:
const willDelete = await swal({
  title: "Are you sure?",
  text: "Are you sure that you want to delete this file?",
  icon: "warning",
  dangerMode: true,
});

if (willDelete) {
  swal("Deleted!", "Your imaginary file has been deleted!", "success");
}

A prompt modal, where the user's input is logged:

  • Using promises:
swal("Type something:", {
  content: "input",
})
.then((value) => {
  swal(`You typed: ${value}`);
});
  • Using async/await:
const value = await swal("Type something:", {
  content: "input",
});

swal(`You typed: ${value}`);

In combination with Fetch:

  • Using promises:
swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(willSearch => {
  if (willSearch) {
    return fetch("http://pokeapi.co/api/v2/pokemon/1");
  }
})
.then(result => result.json())
.then(json => console.log(json))
.catch(err => {
  swal("Oops!", "Seems like we couldn't fetch the info", "error");
});
  • Using async/await:
const willSearch = await swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
});

if (willSearch) {
  try {
    const result = await fetch("http://pokeapi.co/api/v2/pokemon/1");
    const json = await result.json();
    console.log(json);
  } catch (err) {
    swal("Oops!", "Seems like we couldn't fetch the info", "error");
  }
}

Using with React

SweetAlert has tools for integrating with your favourite rendering library..

If you're using React, you can install SweetAlert with React in addition to the main library, and easily add React components to your alerts like this:

import React from 'react'
import swal from '@sweetalert/with-react'

swal(
  <div>
    <h1>Hello world!</h1>
    <p>
      This is now rendered with JSX!
    </p>
  </div>
)

Read more about integrating with React

Contributing

If you're changing the core library:

  1. Make changes in the src folder.
  2. Preview changes by running npm run docs
  3. Submit pull request

If you're changing the documentation:

  1. Make changes in the docs-src folder.
  2. Preview changes by running npm run docs
  3. Run npm run builddocs to compile the changes to the docs folder
  4. Submit pull request

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! Γ°ΒŸΒ™Β [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

NPM DownloadsLast 30 Days