You are on page 1of 37

 

A BEAUTIFUL, RESPONSIVE, CUSTOMIZABLE, ACCESSIBLE (WAI-ARIA)


REPLACEMENT FOR JAVASCRIPT'S POPUP BOXES
ZERO DEPENDENCIES

Create great-looking forms including calculations,


automations and integrations.ads via Carbon
Current version: v9.7.0 ● Latest update: today ● Downloads last month: 527.765
Normal alert
Show normal alert
alert('You clicked the button!')
 
 Show success message
Swal.fire(
'Good job!',
'You clicked the button!',
'success'
)
[==
Become the Ultimate Sponsor of SweetAlert2 and place your banner here
(100K+ unique visitors per month!)
==]

The author of SweetAlert2 (@limonte) is looking for short-term to medium-


term working contracts in front-end, preferably OSS.
EXAMPLES

 A basic message
Try me!
 

Swal.fire('Any fool can use a computer')

 A title with a text under


Try me!
 

Swal.fire(
'The Internet?',
'That thing is still around?',
'question'
)

 A modal with a title, an error icon, a text, and a footer


Try me!
 

Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: '<a href>Why do I have this issue?</a>'
})

 A modal window with a long content inside:


Try me!
 

Swal.fire({
imageUrl: 'https://placeholder.pics/svg/300x1500',
imageHeight: 1500,
imageAlt: 'A tall image'
})
 Custom HTML description and buttons with ARIA labels
Try me!
 

Swal.fire({
title: '<strong>HTML <u>example</u></strong>',
icon: 'info',
html:
'You can use <b>bold text</b>, ' +
'<a href="//sweetalert2.github.io">links</a> ' +
'and other HTML tags',
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
confirmButtonText:
'<i class="fa fa-thumbs-up"></i> Great!',
confirmButtonAriaLabel: 'Thumbs up, great!',
cancelButtonText:
'<i class="fa fa-thumbs-down"></i>',
cancelButtonAriaLabel: 'Thumbs down'
})

 A custom positioned dialog


Try me!
 

Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Your work has been saved',
showConfirmButton: false,
timer: 1500
})

 Custom animation with Animate.css 


Try me!
 

Swal.fire({
title: 'Custom animation with Animate.css',
showClass: {
popup: 'animated fadeInDown faster'
},
hideClass: {
popup: 'animated fadeOutUp faster'
}
})

 A confirm dialog, with a function attached to the "Confirm"-button...


Try me!
 

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.value) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})

 ... and by passing a parameter, you can execute something else for
"Cancel".
Try me!
 

const swalWithBootstrapButtons = Swal.mixin({


customClass: {
confirmButton: 'btn btn-success',
cancelButton: 'btn btn-danger'
},
buttonsStyling: false
})

swalWithBootstrapButtons.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
reverseButtons: true
}).then((result) => {
if (result.value) {
swalWithBootstrapButtons.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
swalWithBootstrapButtons.fire(
'Cancelled',
'Your imaginary file is safe :)',
'error'
)
}
})

 A message with a custom image


Try me!
 

Swal.fire({
title: 'Sweet!',
text: 'Modal with a custom image.',
imageUrl: 'https://unsplash.it/400/200',
imageWidth: 400,
imageHeight: 200,
imageAlt: 'Custom image',
})

 A message with custom width, padding, background and animated


Nyan Cat
Try me!
 

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")
left top
no-repeat
`
})

 A message with auto close timer


Try me!
 

let timerInterval
Swal.fire({
title: 'Auto close alert!',
html: 'I will close in <b></b> milliseconds.',
timer: 2000,
timerProgressBar: true,
onBeforeOpen: () => {
Swal.showLoading()
timerInterval = setInterval(() => {
const content = Swal.getContent()
if (content) {
const b = content.querySelector('b')
if (b) {
b.textContent = Swal.getTimerLeft()
}
}
}, 100)
},
onClose: () => {
clearInterval(timerInterval)
}
}).then((result) => {
/* Read more about handling dismissals below */
if (result.dismiss === Swal.DismissReason.timer) {
console.log('I was closed by the timer')
}
})

 Right-to-left support for Arabic, Persian, Hebrew, and other RTL


languages
Try me!
 

Swal.fire({
title: '‫'هل تريد االستمرار؟‬,
icon: 'question',
iconHtml: '‫'؟‬,
confirmButtonText: '‫'نعم‬,
cancelButtonText: '‫'ال‬,
showCancelButton: true,
showCloseButton: true
})

 AJAX request example


Try me!
 

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.value) {
Swal.fire({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
})
}
})

 Chaining modals (queue) example


Try me!
 
Swal.mixin({
input: 'text',
confirmButtonText: 'Next &rarr;',
showCancelButton: true,
progressSteps: ['1', '2', '3']
}).queue([
{
title: 'Question 1',
text: 'Chaining swal2 modals is easy'
},
'Question 2',
'Question 3'
]).then((result) => {
if (result.value) {
const answers = JSON.stringify(result.value)
Swal.fire({
title: 'All done!',
html: `
Your answers:
<pre><code>${answers}</code></pre>
`,
confirmButtonText: 'Lovely!'
})
}
})

 Dynamic queue example


Try me!
 

const ipAPI = '//api.ipify.org?format=json'

Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
showLoaderOnConfirm: true,
preConfirm: () => {
return fetch(ipAPI)
.then(response => response.json())
.then(data => Swal.insertQueueStep(data.ip))
.catch(() => {
Swal.insertQueueStep({
icon: 'error',
title: 'Unable to get your public IP'
})
})
}
}])

DOWNLOAD & INSTALL


$ npm install sweetalert2

Or grab from jsdelivr CDN 

<script
src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>

sweetalert2 is the 27th most popular package on jsDelivr,


with 366.635.585 CDN hits in the last month

USAGE

1. Initialize the plugin by referencing the necessary files:

<script src="sweetalert2.all.min.js"></script>
<!-- Optional: include a polyfill for ES6 Promises for IE11
-->
<script src="https://cdn.jsdelivr.net/npm/promise-
polyfill"></script>

You can also include the stylesheet separately if desired:

<script src="sweetalert2.min.js"></script>
<link rel="stylesheet" href="sweetalert2.min.css">

Or

// ES6 Modules or TypeScript


import Swal from 'sweetalert2'

// CommonJS
const Swal = require('sweetalert2')

It's possible to import JS and CSS separately, e.g. if you need to customize
styles:

import Swal from 'sweetalert2/dist/sweetalert2.js'


import 'sweetalert2/src/sweetalert2.scss'

2. Call the sweetAlert2-function after the page has loaded

Swal.fire({
title: 'Error!',
text: 'Do you want to continue',
icon: 'error',
confirmButtonText: 'Cool'
})

INTEGRATIONS WITH MAJOR JS


FRAMEWORKS
Angular

React

CONFIGURATION

Here are the keys that you can use if you pass an object into sweetAlert2:

Defa
ult
Argument Description
valu
e
title '' The title of the modal, as HTML. It can either be
added to the object under the key "title" or passed as
the first parameter of the function.

titleText '' The title of the modal, as text. Useful to avoid HTML
injection.

html '' A HTML description for the modal. It can either be


added to the object under the key "html" or passed as
the second parameter of the function.

text '' A description for the modal. If "text" and "html"


parameters are provided in the same time, "text" will
be used.

icon und The icon of the modal. SweetAlert2 comes with 5


efin built-in icon which will show a corresponding icon
ed 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.

iconHtml und The custom HTML content for an icon.


efin
ed

{ CSS classes for animations when showing a popup


showClas
(fade in)
s pop
up:
'sw
al2
-
sho
w',

bac
kdr
op:
'sw
al2
-
bac
kdr
op-
sho
w',

ico
n:
'sw
al2
-
ico
n-
sho
w'
}

hideClass { CSS classes for animations when hiding a popup


(fade out)
pop
up:
'sw
al2
-
hid
e',

bac
kdr
op:
'sw
al2
-
bac
kdr
op-
hid
e',

ico
n:
'sw
al2
-
ico
n-
hid
e'
}

footer '' The footer of the modal. Can be either plain text or
HTML.
backdrop true Whether or not SweetAlert2 should show a full screen
click-to-dismiss backdrop. Can be either a boolean or
a string which will be assigned to the
CSS background property.

toast false Whether or not an alert should be treated as a toast


notification. This option is normally coupled with
the position parameter and a timer. Toasts are
NEVER autofocused.

target 'bod The container element for adding modal into.


y'

input und Input field type, can


efin be text, email, password, number, tel, range, textar
ed ea, select, radio, checkbox, file and url.

width und Modal window width, including paddings (box-


efin sizing: border-box). Can be in px or %. The default
ed width is 32rem.

padding und Modal window padding. The default padding


efin is 1.25rem.
ed

backgrou und Modal window background (CSS background


nd efin property). The default background is '#fff'.
ed

position 'cent Modal window position, can be 'top', 'top-


er' start', 'top-end', 'center', 'center-start', 'center-
end', 'bottom', 'bottom-start', or 'bottom-end'.

grow false Paired with window position, sets the direction the
modal should grow in, can be set
to 'row', 'column', 'fullscreen', or false.

customCl und A custom CSS class for the modal:


ass efin customClass: {
ed container: 'container-class',
popup: 'popup-class',
header: 'header-class',
title: 'title-class',
closeButton: 'close-button-class',
icon: 'icon-class',
image: 'image-class',
content: 'content-class',
input: 'input-class',
actions: 'actions-class',
confirmButton: 'confirm-button-
class',
cancelButton: 'cancel-button-
class',
footer: 'footer-class'
}

timer und Auto close timer of the modal. Set in ms


efin (milliseconds). See
ed also Swal.getTimerLeft(), Swal.stopTimer(), Swal.r
esumeTimer(), Swal.toggleTimer(), Swal.isTimerR
unning() and Swal.increaseTimer().

timerPro false If set to true, the timer will have a progress bar at the
gressBar bottom of a popup. Mostly, this feature is useful with
toasts.

animatio true Deprecated and will be removed in the next major


n release, use showClass and hideClass instead.
If set to false, modal CSS animation will be disabled.

heightAu true By default, SweetAlert2 sets html's and body's


to CSS height to auto !important. If this behavior isn't
compatible with your project's layout,
set heightAuto to false.

allowOut true If set to false, the user can't dismiss the modal by
sideClick clicking outside it.
You can also pass a custom function returning a
boolean value, e.g. if you want to disable outside
clicks for the loading state of a modal.

allowEsc true If set to false, the user can't dismiss the modal by
apeKey pressing the  Esc  key. You can also pass a custom
function returning a boolean value, e.g. if you want to
disable the  Esc  key for the loading state of a modal.

allowEnt true If set to false, the user can't confirm the modal by
erKey pressing the Enter or Space keys, unless they
manually focus the confirm button. You can also pass
a custom function returning a boolean value.

stopKeyd true If set to false, SweetAlert2 will


ownProp allow keydown events propagation to the document.
agation

keydown false Useful for those who are using SweetAlert2 along
Listener with Bootstrap modals. By
Capture default keydownListenerCapture is false which
means when a user hits  Esc , both SweetAlert2 and
Bootstrap modals will be closed.
Set keydownListenerCapture to true to fix that
behavior.

showCon true If set to false, a "Confirm"-button will not be shown.


firmButt It can be useful when you're using custom HTML
on description.

showCan false If set to true, a "Cancel"-button will be shown, which


celButton the user can click on to dismiss the modal.

confirmB 'OK' Use this to change the text on the "Confirm"-button.


uttonTex
t

cancelBu 'Can Use this to change the text on the "Cancel"-button.


ttonText cel'

confirmB und Use this to change the background color of the


uttonCol efin "Confirm"-button. The default color is #3085d6
or ed

cancelBu und Use this to change the background color of the


ttonColo efin "Cancel"-button. The default color is #aaa
r ed

confirmB '' Use this to change the aria-label for the "Confirm"-


uttonAri button.
aLabel

cancelBu '' Use this to change the aria-label for the "Cancel"-


ttonAria button.
Label

buttonsSt true Apply default styling to buttons. If you want to use


yling your own classes (e.g. Bootstrap classes) set this
parameter to false.

reverseB false Set to true if you want to invert default buttons


uttons positions ("Confirm"-button on the right side).

focusCon true Set to false if you want to focus the first element in
firm tab order instead of "Confirm"-button by default.

focusCan false Set to true if you want to focus the "Cancel"-button


cel by default.
showClos false Set to true to show close button in top right corner of
eButton the modal.

closeButt '&ti Use this to change the content of the close button.
onHtml mes;
'

closeButt 'Clo Use this to change the aria-label for the close button.


onAriaL se
abel this
dial
og'

showLoa false Set to true to disable buttons and show that


derOnCo something is loading. Use it in combination with
nfirm the preConfirm parameter.

scrollbar true Set to false to disable body padding adjustment when


Padding the page scrollbar gets hidden while the modal is
shown

preConfi und Function to execute before confirm, may be async


rm efin (Promise-returning) or sync.
ed Returned (or resolved) value can be:
 false to prevent a popup from closing
 anything else to pass that value as
the result.value of Swal.fire()
 undefined to keep the default result.value
See usage example.

imageUrl und Add a customized icon for the modal. Should contain
efin a string with the path or URL to the image.
ed

imageWi und If imageUrl is set, you can specify imageWidth to


dth efin describes image width in px.
ed

imageHei und Custom image height in px.


ght efin
ed

imageAlt '' An alternative text for the custom image icon.

inputPlac '' Input field placeholder.


eholder

inputVal '' Input field initial value.


ue
If the input type is checkbox, inputValue will
represent the checked state.

If the input type


is text, email, number, tel or textarea a Promise can
be accepted as inputValue.

inputOpt {} If input parameter is set to "select" or "radio", you


ions can provide options. Can be a Map or a plain object,
with keys that represent option values and values that
represent option text, or a Promise that resolves with
one of those types.

inputAut true Automatically remove whitespaces from both ends of


oTrim a result string. Set this parameter to false to disable
auto-trimming.

inputAttr {} HTML input attributes


ibutes (e.g. min, max, autocomplete, accept), that are
added to the input field. Object keys will represent
attributes names, object values will represent
attributes values.

inputVali und Validator for input field, may be async (Promise-


dator efin returning) or sync.
ed Returned (or resolved) value can be:
 a falsy value (undefined, null, false) for
indicating success
 a string value (error message) for
indicating failure
See usage example.

validatio und A custom validation message for default validators


nMessag efin (email, url).
e ed

progress [] Progress steps, useful for modal queues, see usage


Steps example.

currentP und Current active progress step. The default


rogressSt efin is Swal.getQueueStep()
ep ed

progress '40p Distance between progress steps.


StepsDist x'
ance
onBefore und Function to run when modal built, but not shown yet.
Open efin Provides modal DOM element as the first argument.
ed

onOpen und Function to run when modal opens, provides modal


efin DOM element as the first argument.
ed

onRende und Function to run after modal DOM has been updated.
r efin Typically, this will happen
ed after Swal.fire() or Swal.update(). If you want to
perform changes in the modal's DOM, that
survive Swal.update(), onRender is a good place for
that.

onClose und Function to run when modal closes by user interaction


efin (and not by another popup), provides modal DOM
ed element as the first argument.

onAfterC und Function to run after popup has been disposed by user
lose efin interaction (and not by another popup).
ed

onDestro und Function to run after popup has been destroyed either
y efin by user interaction or by another popup.
ed

You can easily reuse configuration by creating your own `Swal`


with Swal.mixin({ ...options }):

 Mixin example
Try me!
 

const Toast = Swal.mixin({


toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Signed in successfully'
})

HANDLING DISMISSALS

When an alert is dismissed by the user, the Promise returned


by Swal.fire() will be resolved with an object { dismiss:
reason } documenting the reason it was dismissed:

Reason Description Related configuration

Swal.DismissReason.backdro The user allowOutsideClick


p clicked the
backdrop.

Swal.DismissReason.cancel The user showCancelButton


clicked the
cancel button.

Swal.DismissReason.close The user showCloseButton


clicked the
close button.

Swal.DismissReason.esc The user allowEscapeKey


clicked
the  Esc  key.

Swal.DismissReason.timer The timer ran timer


out, and the
alert closed
automatically.

ICONS
success Try me!

error Try me!

warning
! Try me!

info
i Try me!

question
? Try me!

INPUT TYPES
const ipAPI = '//api.ipify.org? Try
text format=json'
me!
const inputValue = fetch(ipAPI)
.then(response =>
response.json())
.then(data => data.ip)

const { value: ipAddress } = await


Swal.fire({
title: 'Enter your IP address',
input: 'text',
inputValue: inputValue,
showCancelButton: true,
inputValidator: (value) => {
if (!value) {
return 'You need to write
something!'
}
}
})

if (ipAddress) {
Swal.fire(`Your IP address is $
{ipAddress}`)
}

const { value: email } = await


Swal.fire({
title: 'Input email address',
input: 'email',
inputPlaceholder: 'Enter your
email address' Try
email }) me!
if (email) {
Swal.fire(`Entered email: $
{email}`)
}

const { value: url } = await


Swal.fire({
input: 'url',
inputPlaceholder: 'Enter the URL'
Try
url })
me!
if (url) {
Swal.fire(`Entered URL: ${url}`)
}

const { value: password } = await


Swal.fire({
title: 'Enter your password',
input: 'password',
inputPlaceholder: 'Enter your
password',
inputAttributes: {
maxlength: 10,
passwor Try
autocapitalize: 'off',
d autocorrect: 'off' me!
}
})

if (password) {
Swal.fire(`Entered password: $
{password}`)
}

textarea const { value: text } = await Try


Swal.fire({
me!
input: 'textarea',
inputPlaceholder: 'Type your
message here...',
inputAttributes: {
'aria-label': 'Type your
message here'
},
showCancelButton: true
})

if (text) {
Swal.fire(text)
}

const { value: fruit } = await


Swal.fire({
title: 'Select field validation',
input: 'select',
inputOptions: {
apples: 'Apples',
bananas: 'Bananas',
grapes: 'Grapes',
oranges: 'Oranges'
},
inputPlaceholder: 'Select a
fruit',
showCancelButton: true,
inputValidator: (value) => {
return new Promise((resolve) => Try
select { me!
if (value === 'oranges') {
resolve()
} else {
resolve('You need to select
oranges :)')
}
})
}
})

if (fruit) {
Swal.fire(`You selected: $
{fruit}`)
}

radio /* inputOptions can be an object or Try


Promise */
me!
const inputOptions = new
Promise((resolve) => {
setTimeout(() => {
resolve({
'#ff0000': 'Red',
'#00ff00': 'Green',
'#0000ff': 'Blue'
})
}, 1000)
})

const { value: color } = await


Swal.fire({
title: 'Select color',
input: 'radio',
inputOptions: inputOptions,
inputValidator: (value) => {
if (!value) {
return 'You need to choose
something!'
}
}
})

if (color) {
Swal.fire({ html: `You selected:
${color}` })
}

const { value: accept } = await


Swal.fire({
title: 'Terms and conditions',
input: 'checkbox',
inputValue: 1,
inputPlaceholder:
'I agree with the terms and
conditions',
confirmButtonText:
'Continue<i class="fa fa-arrow-
Try
checkbox right"></i>',
inputValidator: (result) => { me!
return !result && 'You need to
agree with T&C'
}
})

if (accept) {
Swal.fire('You agreed with
T&C :)')
}

file const { value: file } = await Try


Swal.fire({
me!
title: 'Select image',
input: 'file',
inputAttributes: {
accept: 'image/*',
'aria-label': 'Upload your
profile picture'
}
})

if (file) {
const reader = new FileReader()
reader.onload = (e) => {
Swal.fire({
title: 'Your uploaded
picture',
imageUrl: e.target.result,
imageAlt: 'The uploaded
picture'
})
}
reader.readAsDataURL(file)
}

Swal.fire({
title: 'How old are you?',
icon: 'question',
input: 'range',
inputAttributes: {
Try
range min: 8,
max: 120, me!
step: 1
},
inputValue: 25
})

Multiple inputs aren't supported, you can achieve them by


using html and preConfirm parameters.
Inside the preConfirm() function you can return (or, if async, resolve with)
the custom result:

const { value: formValues } = await Try me!


Swal.fire({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-
input">' +
'<input id="swal-input2" class="swal2-
input">',
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-
input1').value,
document.getElementById('swal-
input2').value
]
}
})

if (formValues) {
Swal.fire(JSON.stringify(formValues))
}

METHODS
Method Description

Swal.isVisible() Determine if modal is shown.

Swal.mixin({ ...options }) Returns an extended version of `Swal`


containing `params` as defaults. Useful
for reusing Swal configuration.

Swal.update({ ...options }) Updates popup options.

Swal.close() Close the currently open SweetAlert2


modal programmatically, the Promise
returned by Swal.fire() will be resolved
with an empty object { }

Swal.getContainer() Get the popup container which contains


the backdrop.

Swal.getHeader() Get the modal header. The header


contains progress steps, the icon, the
image, the title, and the close button.

Swal.getTitle() Get the modal title.

Swal.getProgressSteps() Get the progress steps.


Swal.getCloseButton() Get the close button.

Swal.getContent() Get the modal content.

Swal.getImage() Get the image.

Swal.getActions() Get the actions block (buttons container).

Swal.getFooter() Get the modal footer.

Swal.getFocusableElements() Get all focusable elements in the popup.

Swal.getConfirmButton() Get the "Confirm" button.

Swal.getCancelButton() Get the "Cancel" button.

Swal.enableButtons() Enable "Confirm" and "Cancel" buttons.

Swal.disableButtons() Disable "Confirm" and "Cancel" buttons.

Swal.showLoading() or Swal.ena Disable buttons and show loader. This is


bleLoading() useful with AJAX requests.

Swal.hideLoading() or Swal.disa Enable buttons and hide loader.


bleLoading()

Swal.isLoading() Determine if modal is in the loading state.


Related
methods: Swal.showLoading() and Swal.
hideLoading()

Swal.getTimerLeft() Returns the time left in case


when timer parameter is set.
Swal.stopTimer() Stops the timer in case
when timer parameter is set. Returns the
time left

Swal.resumeTimer() Resume the timer previously stopped.


Returns the time left

Swal.toggleTimer() Toggle state of the timer between


stopped and running. Returns the time left

Swal.isTimerRunning() Returns the status of a timer: true if is


running, false if it's paused

Swal.increaseTimer(n) Increase the timer by n milliseconds.


Returns the time left

Swal.clickConfirm() Click the "Confirm"-button


programmatically.

Swal.clickCancel() Click the "Cancel"-button


programmatically.

Swal.getInput() Get the input DOM node, this method


works with input parameter.

Swal.disableInput() Disable input. A disabled input element is


unusable and un-clickable.

Swal.enableInput() Enable input.

Swal.showValidationMessage(me Show the validation message DOM node.


ssage)

Swal.resetValidationMessage() Hide the validation message DOM node.


Swal.getValidationMessage() Get the validation message DOM node.

Swal.queue([Array]) Provide array of SweetAlert2 parameters


to show multiple modals, one modal after
another. See usage example

Swal.getQueueStep() Get the index of current modal in queue.


When there's no active queue, null will
be returned.

Swal.insertQueueStep() Insert a modal to queue, you can specify


modal positioning with second parameter.
By default a modal will be added to the
end of a queue.

Swal.deleteQueueStep(index) Delete a modal at index from queue.

Swal.isValidParameter(param) Determine if parameter name is valid.

Swal.isUpdatableParameter(par Determine if parameter name is valid


am) for Swal.update() method.

THEMES 

Dark
Minimal

Borderless
Bootstrap 4

Material UI
WordPress Admin

Themes Installation

You can install all themes at once:


$ npm install @sweetalert2/themes

Or just a single theme @sweetalert2/theme-<theme_name>, e.g.:


$ npm install @sweetalert2/theme-dark

Or from jsdelivr CDN, e.g.:


<link href="//cdn.jsdelivr.net/npm/@sweetalert2/theme-
dark@3/dark.css" rel="stylesheet">
<script
src="//cdn.jsdelivr.net/npm/sweetalert2@9/dist/sweetalert2.mi
n.js"></script>

Themes Usage

With CSS:
<!-- Include a required theme -->
<link rel="stylesheet"
href="@sweetalert2/themes/dark/dark.css">
<script src="sweetalert2/dist/sweetalert2.min.js"></script>

With SASS:
// your-app.js
import Swal from 'sweetalert2/src/sweetalert2.js'

// your-app.scss
@import '~@sweetalert2/themes/dark/dark.scss';

COLLABORATORS
@gverni

@zenflow

@toverux

@acupajoe

DONATIONS

Has SweetAlert2 helped you create an amazing application?


You can show your support by making a donation:

PayPal
GitHub Sponsors

Cryptocurrencies

Hall of Donators 🏆

SPONSORS

Become a sponsor

FlowCrypt
SexualAlpha (NSWF)

STED (NSWF)

YourDoll (NSWF)

PriceListo
LoveLoxy (NSWF)

SebaEBC

Bingato (NSWF 18+)


NDCHost

SheetJS LLC

Unique-P GmbH
STC (NSFW)

Or, click the banner at the top of this page. We show high-quality tech ads
via Carbon.
Ads injected into examples are only shown on this page, they are not the
part of SweetAlert2's codebase and you will not have them when using
SweetAlert2 for your projects.

CONTRIBUTE

Feel free to fork SweetAlert2 on GitHub if you have any features that you
want to add!

You might also like