A beautiful replacement for JavaScript's "alert"

Overview

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 suprises!

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]

Comments
  • input field not functional when used on top of a bootstrap modal

    input field not functional when used on top of a bootstrap modal

    I am currently calling swal from within a bootstrap modal. It seems that the buttons work but the input of the swal is not accepting a click nor does it ever take focus. I'm wondering if this is a known issue or possibly something I'm doing.

    opened by mteichtahl 23
  • Loading State

    Loading State

    Would it be possible to add a "loading" state? For example, with the delete example you would likely want to ask for confirmation (type: warning), update the database (type: loading) and then show a confirmation message (type: success/error).

    new feature 
    opened by pemrouz 23
  • Provider a commonjs entry point for webpack, browserify or any other commonjs module bundler

    Provider a commonjs entry point for webpack, browserify or any other commonjs module bundler

    • build js files from es6 to es5 into lib folder
    • change commonjs entry point to lib/sweetalert.js

    Fix #417 @t4t5 Please checkout this, thx!

    If everything is ok, please merge and bump the version. Thanks for your great work on this lib.

    opened by chentsulin 21
  • Added a cool Input Field option for SweetAlert

    Added a cool Input Field option for SweetAlert

    It is nice to have an input field for an alert to accept user input. I added the following features:

    1. Added a parameter: inputField: (true | false) to enable the input field.
    2. Added the necessary focus() to the input element programatically.
    3. Updated the documentation to include the parameter and to include an example of a use case.

    Update: I added an important fix that I missed on the first commit. That is the commit with the message: "Added fix for running params.doneFunction() without a parameter". Please include the head of master in the merge to get the latest changes.

    help wanted new feature 
    opened by nutterbrand 21
  • Second swal not executed

    Second swal not executed

    Hello,

    I've this sweet-alter call :

    var self = this; 
    
    swal({
          title              : $.t('modal.clear.title') || "Etes vous sûr ?",
          text               : $.t('modal.clear.text') || "Le formulaire sera définitivement perdu !",
          type               : "warning",
          showCancelButton   : true,
          confirmButtonColor : "#DD6B55",
          confirmButtonText  : $.t('modal.clear.yes') || "Oui, supprimer",
          cancelButtonText   : $.t('modal.clear.no') || "Annuler",
          closeOnCancel      : true
    }, function(isConfirm) {
       if (isConfirm){
           // I Use backbone radio event
           self.homePageChannel.trigger('deleteForm', self.currentSelectedForm)
       }
    });
    

    In the callback I send a an event with backbone radio. At this point all is good.

    And in my event response i want to display an another sweet alert like this :

    formDeleted : function(result) {
            swal({
                title : $.t('modal.deleted.title') || 'Formulaire supprimé !',
                text  : $.t('modal.deleted.text') || 'Votre formulaire a été supprimé avec succès',
                type  : "success",
            });
      },
    

    And the second sweet alert doesn't appear. And i'm sure formDeleted function is executed.

    Thanks for your help

    bug 
    opened by amiceli 20
  • Add custom HTML alert support

    Add custom HTML alert support

    Add new alert type: HTML

    EDIT: now using allowHtml option instead of type

    This will allow creating HTML alert box, can be use to create custome dialog types, for example: Prompt, Date picker,...

    Usage:

    swal({   
        title: "Custom dialog!",   
        text: "Here's my <b>HTML</b> <u>message</u>!",   
        type: "success",   
        confirmButtonText: "Yay!",
        allowHtml: true
    });
    
    enhancement 
    opened by huytd 18
  • when i click ok button of sweet alert.. send to another page

    when i click ok button of sweet alert.. send to another page

    i need go to another page after click at ok or error button...my code:

    i use a $(document) because i need show the error when the page is loaded

    pls give me a hand ;)

    opened by fabianchoxD 17
  • [FEATURE] - prompt

    [FEATURE] - prompt

    Here is my pull request of prompt feature. Requested in #155

    I also updated example website with documentation.

    Here is live example - http://mirokoczka.eu/sweetalert/example

    duplicate 
    opened by mkoczka 16
  • SweetAlert open callback

    SweetAlert open callback

    Hello,

    Is there any callback that I could use when SweetAlert is totally opened? I need to use some preloading sutff for SweetAlert content, however I was not able to find a callback to allow me to do this.

    Any ideas?

    opened by IvoPereira 15
  • Popup closing immediately on IE11 (and WP 8.1)

    Popup closing immediately on IE11 (and WP 8.1)

    Trying SweetAlert on your website, I noticed the samples all immediately close after they open, but the timer example which does not seem to open at all. I'm using Windows Phone 8.1, which uses Internet Explorer 11 (Nokia Lumia 920)

    bug 
    opened by christianrondeau 15
  • Wait until getModal returns the correct value

    Wait until getModal returns the correct value

    In response to https://github.com/t4t5/sweetalert/issues/53

    the function is split to two swal and modalDependant

    call getModal to see if it returns null or not, if it does return null then start an interval with 100ms and check if it returns null until it does not return null and then call the modalDependant() function, previously swal

    opened by panihans 15
  • Alert with only an icon and title is missing bottom spacing

    Alert with only an icon and title is missing bottom spacing

    The issue

    When creating an alert with only a title and icon, the spacing at the bottom that is usually provided when using buttons or text is not rendered.

    For example, doing the following,

    swal({
      title: "Example Title",
      icon: "error",
      buttons: false
    });
    

    will render,

    image

    Expectation

    I would expect that there is spacing similar to when text is provided:

    image

    Possible Solution

    One solution I see is to apply the bottom spacing like the margin for text is added, something like:

    .swal-title:last-child {
      margin-bottom: 45px;
    }
    

    This would then give,

    image

    opened by brentvollebregt 0
  • Unpkg sweetalert unavalable

    Unpkg sweetalert unavalable

    Hi,

    The url https://unpkg.com/sweetalert/dist/sweetalert.min.js, is unavalable.

    So if you have this import in your code you will not be able to have the sweetalert.

    For the users, my temporary advise is use the alternative official url: https://cdn.jsdelivr.net/npm/sweetalert The new import:

    But will be important to solve the primary problem, as soon as you have the primary resource available please let us know. Thank you!

    Have a nice day.

    opened by miguelsoeiro 0
  • Typescript error

    Typescript error

    I am getting this error while using sweetalertjs with react-ts Code

    swal("Are you sure?", { dangerMode: true, buttons: true, });

    Type 'true' is not assignable to type 'ButtonList | (string | boolean)[] | undefined'.ts(2322)

    opened by mugishap 0
  • LMS joomla

    LMS joomla

    Hi! I install sweetalert on my rise course.. when i export in web format everything work perfectly.. i did some changes, colors modification etc.. I export for scrom 1.2 and i did all the change in the content ( add .js, etc.. ) but the lms dont want to add my scroms.. I can use sweet alert on the lms right?

    Thanks in advance :)

    Berta

    opened by Bertarose 0
  • Bump path-parse from 1.0.5 to 1.0.7

    Bump path-parse from 1.0.5 to 1.0.7

    Bumps path-parse from 1.0.5 to 1.0.7.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v2.1.0)
  • v2.0.6(Oct 10, 2017)

  • v2.0.3(Sep 8, 2017)

    • Styling now gets injected at the top of the <head> instead of the bottom, so that the user can easily overwrite the CSS.
    • Make text in content visible by settings font-size: initial
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Sep 7, 2017)

  • v2.0.0(Sep 6, 2017)

    A major new release of SweetAlert is finally out, with many new features and improvements, including:

    • Promise-based API
    • Ability to add more than 2 buttons!
    • Ability to create customised modals through the content option

    Make sure you read the upgrade guide and check out the new website to learn about all the new features!

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Oct 20, 2015)

  • v1.1.0(Jul 29, 2015)

    Changelog:

    • Show a loader on the confirm-button with showLoaderOnConfirm: true (handy for AJAX requests that can take some time to validate).
    • Some simple QUnit tests will now run automatically when running gulp. This should make it easier for us not to break anything in upcoming releases (I've only added the most basic ones, pull requests for more tests are very welcome!)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(May 21, 2015)

    Here we go! We've finally reached 1.0.0! This release mostly fixes the bugs from 1.0.0-beta.

    Changelog:

    • Bug fix: Require.js support should work again! Thanks @jeremylevy!
    • Allow a default input value with inputValue: "My text"
    • When using the timer, you can now specify callbacks which will execute when the timer is done, just like you do when clicking the Done-button!
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-beta(Apr 16, 2015)

    The goal of this release is to set things right and move to a more maintainable project structure so that new features can be pushed out easily. It will stay in beta for about a week, and during the time we welcome feedback and small bug fixes. Shortly after that, the final v1.0.0 will be released.

    Changelog:

    • Themes! You can now experiment with new looks for your SweetAlert. The project comes with three themes that you can try out: Facebook, Twitter and Google (in the themes-folder).
    • ES6 syntax! The project is now much more maintainable as the main JS-file has been split up into several es6-modules instead. The main file is dev/sweetalert.es6.js, which should be edited while Gulp is running in order to compile it with Babel.
    • BREAKING CHANGE the files that you need to reference in order to use SweetAlert in your project have been relocated an renamed. They are dist/sweetalert.min.js and dist/sweetalert.css.
    • GitHub page. This will make the project page stay in sync with the latest version.
    • inputPlaceholder when using type: input
    • IE8 support has been dropped. Some might be disappointed by this, but in order to move the project forward, we can't stick with these ancient browsers. If IE8 users are your primary customers, you probably don't need SweetAlert anyway, use a good ol' alert.
    • Bug fixes: allowOutsideClick: false works again
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Mar 19, 2015)

    Changelog:

    • Prompt feature (finally)! You can now pass in type: "input" to get a sweet looking prompt from SweetAlert! Check out the docs and examples to learn more about how to configure and validate the input field.
    • Two new animations: "slide-from-top" and "slide-from-bottom", which can be set through the animation param.
    • Clicking outside the modal now calls the callback function (if it exists), just like when you click the Cancel-button.
    • Possibility to disable confirm button color style manipulation by padding confirmButtonColor: false
    • Page scrolling is now deactivated when the input is shown.
    • Added a link to the SweetAlert tutorial on Ludu
    • Other smaller bug fixes
    Source code(tar.gz)
    Source code(zip)
  • v0.4.2(Feb 11, 2015)

    Changelog:

    • You can now install SweetAlert through NPM. Just run npm install sweetalert to get started!
    • AMD & CommonJS support! You can now avoid running SweetAlert as a global function if you want to. Thanks @danreeves and everyone else who has suggested this enhancement!
    • Ability to hide "OK/Confirm"-button with showConfirmButton: false. This can be used if you prefer using a timer, or in combination with allowOutsideClick.
    • Removal of generic class names (such as .confirm, .success... etc). All classes are now prefixed with .sa- to remove potential conflicts with your own stylesheets. Thanks @sushantdhiman!
    Source code(tar.gz)
    Source code(zip)
  • v0.4.1(Jan 20, 2015)

    Changelog:

    • Add IE8 and IE9 support.
    • Update README with browser compatibility info
    • Initialize DOM elements on first usage instead of on page load (Thanks @peterjosling!)
    • [BUGFIX] Fix custom image size attribute
    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Jan 18, 2015)

    Changelog:

    • Add NPM and Gulp file for automatic minification
    • Escape key now closes all modals
    • Programatically close modals with swal.close()
    • Fix bug to change the OK-button's text to "Confirm" when showing the cancel-button
    • Add html parameter to allow HTML code in modals
    • Allow the modal animation to be turned off by passing animation: false
    Source code(tar.gz)
    Source code(zip)
Owner
Tristan Edwards
Designer/developer. Builder of @Ludu. Maker of codespace.app
Tristan Edwards
⛔️ DEPRECATED - Dependency-free notification library that makes it easy to create alert - success - error - warning - information - confirmation messages as an alternative the standard alert dialog.

DEPRECATED This repository is no longer supported, please consider using alternatives. Dependency-free notification library. Documentation » Hi NOTY i

Nedim Arabacı 6.7k Dec 21, 2022
Custom alert box using javaScript and css. This plugin will provide the functionality to customize the default JavaScript alert box.

customAlertBoxPlugin Custom Alert Box Plugin Using JavaScript and CSS Author: Suraj Aswal Must Include CSS Code/Default Custom Alert Box Class: /* mus

Suraj Aswal 17 Sep 10, 2022
A Powerful and Elegant "alert" library for JavaScript that replaces that boring alert style of Javascript.

A Powerful , Elegant and fully customizable "alert" library using JavaScript that replaces that boring style of alert. Installation Place the below sc

Cosmogic 11 Aug 10, 2021
It's an alert library build with JavaScript. You can replace your traditional JavaScript alert, confirm and toast with the library.

asteroid-alert It's an alert library build with JavaScript. You can replace your traditional JavaScript alert, confirm with the library. It has also e

Khan Md Sagar 4 Mar 12, 2021
Simple translation for your javascripts, yummy with your favorite templates engine like EJS.

jsperanto Simple translation for your javascripts, yummy with your favorite templates engine like EJS. Pluralization, interpolation & "nested lookup"

Jean-Philippe Joyal 62 Oct 21, 2021
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A beautiful, responsive, highly customizable and accessible replacement for JavaScript's popup boxes. Zero dependencies.Alerts ,dialogs

AsgarAlert (v1) for JS Install <script defer src="/asgar-alert.js"></script> Examples The most basic message: asgar("Hello world!"); A message signali

Asgar Aliyev 5 Dec 20, 2022
SPOILER ALERT! A happy little bit of javascript to hide spoilers on your site.

SPOILER ALERT! Don't spoil it! Hide copy and images with a bit of SVG blur. Taste on mouseover. Eat on click. Do you publish spoilers? Do you wish you

Joshua Hull 473 Sep 27, 2022
framework-agnostic styled alert system for javascript

SMOKE.JS - 0.1.3 Notify or get approval from your users quickly and with style. This alert system uses css animations and background (so there are no

j youngblood 934 Dec 25, 2022
A customizable lightweight Alert Library with Material UI and awesome features.

SoloAlert A customizable lightweight Alert Library with Material UI and awesome features. view soloalert on npm : https://www.npmjs.com/soloalert Inst

Arnav Kumar 21 Nov 30, 2022
Simple to use modal / alert / dialog / popup. Created with vanilla JS. No javascript knowledge required! Works on every browser and device! IE9

EinsModal The last modal / alert / dialog you will ever need! Full Documentation: https://www.einscms.com/modal EinsModal is the best solution to inte

EinsCMS 30 Oct 20, 2022
An alarm clock is a clock that is designed to alert an individual or group of individuals at a specified time.

An alarm clock (or sometimes just an alarm) is a clock that is designed to alert an individual or group of individuals at a specified time. The primary function of these clocks is to awaken people from their night's sleep or short naps; they are sometimes used for other reminders as well.

Anupam Moharana 1 Dec 25, 2021
React Native's Global Alert Component that can be fully customized and without the need of a state.

?? React Native Easy Alert React Native Easy Alert Component. Watch on youtube Easy Alert example app. React Native's Global Alert Component that can

null 9 Feb 21, 2022
đź”” Get an alert on Telegram when there are Raspberry in stock ready to buy

Raspberry instock check bot Get an alert on Telegram when there are Raspberry in stock ready to buy. This bot uses the website https://rpilocator.com/

null 38 Dec 16, 2022
JavaScript Alert/Notification System

alertify.js - browser dialogs never looked so good The end of maintenance... at least for now Unfortunately, I will no longer be maintaining alertify.

Fabien Doiron 4.3k Dec 22, 2022
A simple, jQuery free Snackbar (Toast) alert

js-snackbar What is a SnackBar? According to Material Design a Snackbar or Toast provides "brief messages about app processes at the bottom of the scr

Michael Mickelson 43 Jan 5, 2023
🦄 0-legacy, tiny & fast web framework as a replacement of Express

tinyhttp ⚡ Tiny web framework as a replacement of Express ?? tinyhttp now has a Deno port (work in progress) tinyhttp is a modern Express-like web fra

v 1 r t l 2.4k Jan 3, 2023
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

Select2 Select2 is a jQuery-based replacement for select boxes. It supports searching, remote data sets, and pagination of results. To get started, ch

Select2 25.5k Jan 1, 2023