Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (625.52 KB, 42 trang )
ExamplesInstallationUsageIntegrationsConfigurationDismissalsIconsInput
TypesMethodsCollaboratorsThemesDonationsSponsorsNSFW Sponsors
Share the
Default
Theme:
Version:
9.x
A BEAUTIFUL, RESPONSIVE, CUSTOMIZABLE, ACCESSIBLE (WAI-ARIA)
REPLACEMENT FOR JAVASCRIPT'S POPUP BOXES
ZERO DEPENDENCIES
Deploy more with Linux VMs, S3-compatible object storage & global
infrastructure. $100 in free credits.A D S
V IA CA R B ON
Current version: v9.17.1 ● Latest update: 3 days ago ● Downloads last month: 855,013
Normal alert
Show normal alert
alert('You clicked the button!')
Show success message
Swal.fire(
'Good job!',
'You clicked the button!',
'success'
)
<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=" />
sweetalert2 is the 23rd most popular package on jsDelivr,
with 439,039,852 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=" />
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:
Argument
(Default
value)
Description
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
undefined
The icon of the modal. SweetAlert2 comes with 5 built-in icon which
will show a corresponding icon
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
undefined
The custom HTML content for an icon.
showClass
CSS classes for animations when showing a popup (fade in)
{
popup:
'swal2show',
backdrop:
'swal2backdropshow',
icon:
'swal2iconshow'
}
hideClass
{
popup:
'swal2hide',
backdrop:
'swal2backdrophide',
icon:
'swal2-
CSS classes for animations when hiding a popup (fade out)
iconhide'
}
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
'body'
The container element for adding modal into.
input
undefined
Input field type, can
be text, email, password, number, tel, range, textarea, select, radio,
checkbox, file and url.
width
undefined
Modal window width, including paddings (box-sizing: border-box).
Can be in px or %. The default width is 32rem.
padding
undefined
Modal window padding. The default padding is 1.25rem.
background
undefined
Modal window background (CSS background property). The default
background is '#fff'.
position
'center'
Modal window position, can be 'top', 'top-start', 'topend', '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.
customClass
undefined
A custom CSS class for the modal:
customClass: {
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
undefined
Auto close timer of the modal. Set in ms (milliseconds). See
also Swal.getTimerLeft(), Swal.stopTimer(), Swal.resumeTimer(),
Swal.toggleTimer(), Swal.isTimerRunning() and Swal.increaseTim
er().
timerProgre
ssBar
false
If set to true, the timer will have a progress bar at the bottom of a
popup. Mostly, this feature is useful with toasts.
animation
true
Deprecated and will be removed in the next major release,
use showClass and hideClass instead:
Swal.fire({
...,
showClass: {
popup: 'swal2-noanimation',
backdrop: 'swal2-noanimation'
},
hideClass: {
popup: '',
backdrop: ''
}
})
If set to false, modal CSS animation will be disabled.
heightAuto
true
By default, SweetAlert2 sets html's and body's CSS height to auto !
important. If this behavior isn't compatible with your project's layout,
set heightAuto to false.
allowOutsid
eClick
true
If set to false, the user can't dismiss the modal by 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.
allowEscape
Key
true
If set to false, the user can't dismiss the modal by 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.
allowEnter
Key
true
If set to false, the user can't confirm the modal by pressing the Enter or
Space keys, unless they manually focus the confirm button. You can
also pass a custom function returning a boolean value.
stopKeydow
nPropagatio
n
true
If set to false, SweetAlert2 will allow keydown events propagation to
the document.
keydownLis
tenerCaptur
e
false
Useful for those who are using SweetAlert2 along with Bootstrap
modals. By 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.
showConfir
mButton
true
If set to false, a "Confirm"-button will not be shown. It can be useful
when you're using custom HTML description.
showCancel
Button
false
If set to true, a "Cancel"-button will be shown, which the user can
click on to dismiss the modal.
confirmButt
onText
'OK'
Use this to change the text on the "Confirm"-button.
cancelButto
nText
'Cancel'
Use this to change the text on the "Cancel"-button.
confirmButt
onColor
undefined
Use this to change the background color of the "Confirm"-button. The
default color is #3085d6
cancelButto
nColor
undefined
Use this to change the background color of the "Cancel"-button. The
default color is #aaa
confirmButt
onAriaLabel
''
Use this to change the aria-label for the "Confirm"-button.
cancelButto
nAriaLabel
Use this to change the aria-label for the "Cancel"-button.
''
buttonsStyli
ng
true
Apply default styling to buttons. If you want to use your own classes
(e.g. Bootstrap classes) set this parameter to false.
reverseButt
ons
false
Set to true if you want to invert default buttons positions ("Confirm"button on the right side).
focusConfir
m
true
Set to false if you want to focus the first element in tab order instead of
"Confirm"-button by default.
focusCancel
false
Set to true if you want to focus the "Cancel"-button by default.
showCloseB
utton
false
Set to true to show close button in top right corner of the modal.
closeButton
Html
'×'
Use this to change the content of the close button.
closeButton
AriaLabel
'Close this
dialog'
Use this to change the aria-label for the close button.
showLoader
OnConfirm
false
Set to true to disable buttons and show that something is loading. Use
it in combination with the preConfirm parameter.
scrollbarPa
dding
true
Set to false to disable body padding adjustment when the page
scrollbar gets hidden while the modal is shown
preConfirm
undefined
Function to execute before confirm, may be async (Promise-returning)
or sync.
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
undefined
Add a customized icon for the modal. Should contain a string with the
path or URL to the image.
imageWidth
undefined
If imageUrl is set, you can specify imageWidth to describes image
width in px.
imageHeight
undefined
Custom image height in px.
imageAlt
''
An alternative text for the custom image icon.
inputPlaceh
older
''
Input field placeholder.
inputValue
''
Input field initial value.
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.
inputOption
s
{}
If input parameter is set to "select" or "radio", you can provide
options. Can be a Map or a plain object, with keys that represent
option values and values that represent option text. You can also
provide plain object or Map as values that will represented a group of
options, being the label of this <optgroup> the key. Finally, you can
also provide a Promise that resolves with one of those types.
inputAutoTr
im
true
Automatically remove whitespaces from both ends of a result string.
Set this parameter to false to disable auto-trimming.
inputAttrib
HTML input attributes (e.g. min, max, autocomplete, accept), that
utes
{}
are added to the input field. Object keys will represent attributes
names, object values will represent attributes values.
inputValidat
or
undefined
Validator for input field, may be async (Promise-returning) or sync.
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.
validationM
essage
undefined
A custom validation message for default validators (email, url).
progressSte
ps
[]
Progress steps, useful for modal queues, see usage example.
currentProg
ressStep
undefined
Current active progress step. The default is Swal.getQueueStep()
progressSte
psDistance
'40px'
Distance between progress steps.
onBeforeOp
en
undefined
Function to run when modal built, but not shown yet. Provides modal
DOM element as the first argument.
onOpen
undefined
Function to run when modal opens, provides modal DOM element as
the first argument.
onRender
undefined
Function to run after modal DOM has been updated. Typically, this
will happen 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
undefined
Function to run when modal closes by user interaction (and not by
another popup), provides modal DOM element as the first argument.
onAfterClos
Function to run after popup has been disposed by user interaction (and
e
undefined
not by another popup).
onDestroy
undefined
Function to run after popup has been destroyed either by user
interaction or by another popup.
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.backdrop
The user clicked the
backdrop.
allowOutsideClick
Swal.DismissReason.cancel
The user clicked the
cancel button.
showCancelButton
Swal.DismissReason.close
The user clicked the
close button.
showCloseButton
Swal.DismissReason.esc
The user clicked
the Esc key.
allowEscapeKey
Swal.DismissReason.timer
The timer ran out, and
the alert closed
automatically.
timer
ICONS
success
Try me!
error
Try me!
warning
!
Try me!
info
i
Try me!
?
question
Try me!
INPUT TYPES
const ipAPI = '//api.ipify.org?
format=json'
const inputValue = fetch(ipAPI)
.then(response => response.json())
.then(data => data.ip)
text
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!'
}
}
})
Try
me!
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'
})
if (email) {
Try
me!
Swal.fire(`Entered email: ${email}`)
}
url
const { value: url } = await Swal.fire({
input: 'url',
inputPlaceholder: 'Enter the URL'
})
if (url) {
Swal.fire(`Entered URL: ${url}`)
}
passwo
rd
const { value: password } = await
Swal.fire({
title: 'Enter your password',
input: 'password',
inputPlaceholder: 'Enter your
password',
inputAttributes: {
maxlength: 10,
autocapitalize: 'off',
autocorrect: 'off'
}
})
Try
me!
Try
me!
if (password) {
Swal.fire(`Entered password: $
{password}`)
}
textare
a
const { value: text } = await
Swal.fire({
input: 'textarea',
inputPlaceholder: 'Type your message
here...',
inputAttributes: {
'aria-label': 'Type your message
here'
},
showCancelButton: true
})
Try
me!
if (text) {
Swal.fire(text)
}
select
const { value: fruit } = await
Try
Swal.fire({
title: 'Select field validation',
input: 'select',
inputOptions: {
'Fruits': {
apples: 'Apples',
bananas: 'Bananas',
grapes: 'Grapes',
oranges: 'Oranges'
},
'Vegetables': {
potato: 'Potato',
broccoli: 'Broccoli',
carrot: 'Carrot'
},
'icecream': 'Ice cream'
},
inputPlaceholder: 'Select a fruit',
showCancelButton: true,
inputValidator: (value) => {
return new Promise((resolve) => {
if (value === 'oranges') {
resolve()
} else {
resolve('You need to select
oranges :)')
}
})
}
})
me!
if (fruit) {
Swal.fire(`You selected: ${fruit}`)
}
radio
/* inputOptions can be an object or
Promise */
const inputOptions = new
Promise((resolve) => {
setTimeout(() => {
resolve({
'#ff0000': 'Red',
'#00ff00': 'Green',
'#0000ff': 'Blue'
})
}, 1000)
})
Try
me!
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}` })
}
checkb
ox
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-arrowright"></i>',
inputValidator: (result) => {
return !result && 'You need to agree
with T&C'
}
})
Try
me!
if (accept) {
Swal.fire('You agreed with T&C :)')
}
file
const { value: file } = await
Swal.fire({
title: 'Select image',
input: 'file',
inputAttributes: {
'accept': 'image/*',
'aria-label': 'Upload your profile
picture'
}
Try
me!