Ecco un confronto con un messaggio di errore standard Il primo uso il messaggio di allerta standard di sistema. Il secondo invece utilizza la funzione SweetAlert2.
alert('Oops! Something went wrong!')
swal( 'Oops...', 'Something went wrong!', 'error' )
Carino vero? SweetAlert2 si centra automaticamente sulla pagina, ha un bell'aspetto indipendentemente dal fatto che si utilizzi PC, Tablet o Cellulare. Altamente personalizzabile come puoi vedere qui sotto.
Un titolo con testo descrittivo
swal( 'The Internet?', 'That thing is still around?', 'question' )
A messaggio di successo!
swal( 'Good job!', 'You clicked the button!', 'success' )
Messaggio cin timer di chiusura automatica
swal({ title: 'Auto close alert!', text: 'I will close in 2 seconds.', timer: 2000 }).then( function () {}, // handling the promise rejection function (dismiss) { if (dismiss === 'timer') { console.log('I was closed by the timer') } } )
Pulsanti e descrizione HTML personalizzati
swal({ title: '<i>HTML</i> <u>example</u>', type: 'info', html: 'You can use <b>bold text</b>, ' + '<a href="//github.com">links</a> ' + 'and other HTML tags', showCloseButton: true, showCancelButton: true, confirmButtonText: '<i class="fa fa-thumbs-up"></i> Great!', cancelButtonText: '<i class="fa fa-thumbs-down"></i>' })
jQuery HTML con animazione personalizzata (Animate.css )
swal({ title: 'jQuery HTML example', html: $('<div>') .addClass('some-class') .text('jQuery is everywhere.'), animation: false, customClass: 'animated tada' })
Messaggio di avviso con pulsante conferma...
swal({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then(function () { swal( 'Deleted!', 'Your file has been deleted.', 'success' ) })
e passando un parametro, puoi eseguire qualcos' altro con "Annulla"
swal({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!', cancelButtonText: 'No, cancel!', confirmButtonClass: 'btn btn-success', cancelButtonClass: 'btn btn-danger', buttonsStyling: false }).then(function () { swal( 'Deleted!', 'Your file has been deleted.', 'success' ) }, function (dismiss) { // dismiss can be 'cancel', 'overlay', // 'close', and 'timer' if (dismiss === 'cancel') { swal( 'Cancelled', 'Your imaginary file is safe :)', 'error' ) } })
Un messaggio con immagine personalizzata e un' animazione css disabilitata.
swal({ title: 'Sweet!', text: 'Modal with a custom image.', imageUrl: 'https://unsplash.it/400/200', imageWidth: 400, imageHeight: 200, animation: false })
swal({ title: 'Custom width, padding, background.', width: 600, padding: 100, background: '#fff url(//bit.ly/1Nqn9HU)' })
Esempio di richiesta Ajax
swal({ title: 'Submit email to run ajax request', input: 'email', showCancelButton: true, confirmButtonText: 'Submit', showLoaderOnConfirm: true, preConfirm: function (email) { return new Promise(function (resolve, reject) { setTimeout(function() { if (email === 'taken@example.com') { reject('This email is already taken.') } else { resolve() } }, 2000) }) }, allowOutsideClick: false }).then(function (email) { swal({ type: 'success', title: 'Ajax request finished!', html: 'Submitted email: ' + email }) })
swal.setDefaults({ input: 'text', confirmButtonText: 'Next →', showCancelButton: true, animation: false, progressSteps: ['1', '2', '3'] }) var steps = [ { title: 'Question 1', text: 'Chaining swal2 modals is easy' }, 'Question 2', 'Question 3' ] swal.queue(steps).then(function (result) { swal.resetDefaults() swal({ title: 'All done!', html: 'Your answers: <pre>' + JSON.stringify(result) + '</pre>', confirmButtonText: 'Lovely!', showCancelButton: false }) }, function () { swal.resetDefaults() })
Esempio di coda dinamica
swal.queue([{ title: 'Your public IP', confirmButtonText: 'Show my public IP', text: 'Your public IP will be received ' + 'via AJAX request', showLoaderOnConfirm: true, preConfirm: function () { return new Promise(function (resolve) { $.get('https://api.ipify.org?format=json') .done(function (data) { swal.insertQueueStep(data.ip) resolve() }) }) } }])
$ bower install sweetalert2
Oppure
$ npm install sweetalert2
Oppure download da CDN: jsdelivr.com/sweetalert2 | cdnjs.com/limonte-sweetalert2
1. Inizializza il plugin facendo riferimento ai file necessari :
<script src="bower_components/sweetalert2/dist/sweetalert2.min.js"></script> <link rel="stylesheet" href="bower_components/sweetalert2/dist/sweetalert2.min.css"> <!-- Include a polyfill for ES6 Promises (optional) for IE11 and Android browser --> <script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.js"></script>
Oppure
// ES6 Modules import { default as swal } from 'sweetalert2' // CommonJS const swal = require('sweetalert2')
2. Chiama la funzione sweetAlert2 dopo che la pagina è stata caricata
swal({ title: 'Error!', text: 'Do you want to continue', type: 'error', confirmButtonText: 'Cool' })
Queste le chiavi da usara per passare un oggetto a sweetAlert2:
Argument | Default value | Description |
---|---|---|
title | null | 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 | null | The title of the modal, as text. Useful to avoid HTML injection. |
text | null | A description for the modal. It can either be added to the object under the key "text" or passed as the second parameter of the function. |
html | null | A HTML description for the modal. If "text" and "html" parameters are provided in the same time, "text" will be used. |
type | null | The type of the modal. SweetAlert2 comes with 5 built-in types which will show a corresponding icon animation: warning, error, success, info and question. It can either be put in the array under the key "type" or passed as the third parameter of the function. |
target | 'body' | The container element for adding modal into. |
input | null | Input field type, can be text, email, password, number, tel, range, textarea, select, radio, checkbox, file and url. |
width | '500px' | Modal window width, including paddings (box-sizing: border-box). Can be in px or %. |
padding | 20 | Modal window padding. |
background | '#fff' | Modal window background (CSS background property). |
customClass | null | A custom CSS class for the modal. |
timer | null | Auto close timer of the modal. Set in ms (milliseconds). |
animation | true | If set to false, modal CSS animation will be disabled. |
allowOutsideClick | true | If set to false, the user can't dismiss the modal by clicking outside it. |
allowEscapeKey | true | If set to false, the user can't dismiss the modal by pressing the Escape key. |
allowEnterKey | 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. |
showConfirmButton | true | If set to false, a "Confirm"-button will not be shown. It can be useful when you're using custom HTML description. |
showCancelButton | false | If set to true, a "Cancel"-button will be shown, which the user can click on to dismiss the modal. |
confirmButtonText | 'OK' | Use this to change the text on the "Confirm"-button. |
cancelButtonText | 'Cancel' | Use this to change the text on the "Cancel"-button. |
confirmButtonColor | '#3085d6' | Use this to change the background color of the "Confirm"-button (must be a HEX value). |
cancelButtonColor | '#aaa' | Use this to change the background color of the "Cancel"-button (must be a HEX value). |
confirmButtonClass | null | A custom CSS class for the "Confirm"-button. |
cancelButtonClass | null | A custom CSS class for the "Cancel"-button. |
buttonsStyling | true | Apply default swal2 styling to buttons. If you want to use your own classes (e.g. Bootstrap classes) set this parameter to false. |
reverseButtons | false | Set to true if you want to invert default buttons positions ("Confirm"-button on the right side). |
focusCancel | false | Set to true if you want to focus the "Cancel"-button by default. |
showCloseButton | false | Set to true to show close button in top right corner of the modal. |
showLoaderOnConfirm | false | Set to true to disable buttons and show that something is loading. Useful for AJAX requests. |
preConfirm | null | Function to execute before confirm, should return Promise, see usage example. |
imageUrl | null | Add a customized icon for the modal. Should contain a string with the path or URL to the image. |
imageWidth | null | If imageUrl is set, you can specify imageWidth to describes image width in px. |
imageHeight | null | Custom image height in px. |
imageClass | null | A custom CSS class for the customized icon. |
inputPlaceholder | '' | Input field placeholder. |
inputValue | '' | Input field initial value. |
inputOptions | {} or Promise | If input parameter is set to "select" or "radio", you can provide options. Object keys will represent options values, object values will represent options text values. |
inputAutoTrim | true | Automatically remove whitespaces from both ends of a result string. Set this parameter to false to disable auto-trimming. |
inputAttributes | {} | HTML input attributes (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. |
inputValidator | null | Validator for input field, should return Promise, see usage example. |
inputClass | null | A custom CSS class for the input field. |
progressSteps | [] | Progress steps, useful for modal queues, see usage example. |
currentProgressStep | null | Current active progress step. The default is swal.getQueueStep() |
progressStepsDistance | '40px' | Distance between progress steps. |
onOpen | null | Function to run when modal opens, provides modal DOM element as the first argument. |
onClose | null | Function to run when modal closes, provides modal DOM element as the first argument. |
Possibile ridefinire i parametri predefiniti usando: swal.setDefaults(customParams).
Quando un avviso viene eliminato dall'utente, la promessa restituita da swal() sarà rifiutata con una stringa documentante le motivazioni del rifiuto:
String | Description | Related configuration |
---|---|---|
'overlay' | The user clicked the overlay. | allowOutsideClick |
'cancel' | The user clicked the cancel button. | showCancelButton |
'close' | The user clicked the close button. | showCloseButton |
'esc' | The user clicked the Esc key. | allowEscapeKey |
'timer' | The timer ran out, and the alert closed automatically. | timer |
Se i respingimenti non vengono gestiti, verrà registrato un errore. Per
evitare questo aggiungi un gestore di rifiuto alla Promessa.
In alternativa puoi usare .catch(swal.noop) come modo
rapido per sopprimere semplicemente gli errori.
swal(...) .catch(swal.noop)
success | ||
error | ||
warning | ||
info | ||
question |
text |
swal({ title: 'Input something', input: 'text', showCancelButton: true, inputValidator: function (value) { return new Promise(function (resolve, reject) { if (value) { resolve() } else { reject('You need to write something!') } }) } }).then(function (result) { swal({ type: 'success', html: 'You entered: ' + result }) }) |
|
swal({ title: 'Input email address', input: 'email' }).then(function (email) { swal({ type: 'success', html: 'Entered email: ' + email }) }) |
||
password |
swal({ title: 'Enter your password', input: 'password', inputAttributes: { 'maxlength': 10, 'autocapitalize': 'off', 'autocorrect': 'off' } }).then(function (password) { if (password) { swal({ type: 'success', html: 'Entered password: ' + password }) } }) |
|
textarea |
swal({ input: 'textarea', showCancelButton: true }).then(function (text) { if (text) { swal(text) } }) |
|
select |
swal({ title: 'Select Ukraine', input: 'select', inputOptions: { 'SRB': 'Serbia', 'UKR': 'Ukraine', 'HRV': 'Croatia' }, inputPlaceholder: 'Select country', showCancelButton: true, inputValidator: function (value) { return new Promise(function (resolve, reject) { if (value === 'UKR') { resolve() } else { reject('You need to select Ukraine :)') } }) } }).then(function (result) { swal({ type: 'success', html: 'You selected: ' + result }) }) |
|
radio |
// inputOptions can be an object or Promise var inputOptions = new Promise(function (resolve) { setTimeout(function () { resolve({ '#ff0000': 'Red', '#00ff00': 'Green', '#0000ff': 'Blue' }) }, 2000) }) swal({ title: 'Select color', input: 'radio', inputOptions: inputOptions, inputValidator: function (result) { return new Promise(function (resolve, reject) { if (result) { resolve() } else { reject('You need to select something!') } }) } }).then(function (result) { swal({ type: 'success', html: 'You selected: ' + result }) }) |
|
checkbox |
swal({ title: 'Terms and conditions', input: 'checkbox', inputValue: 1, inputPlaceholder: 'I agree with the terms and conditions', confirmButtonText: 'Continue <i class="fa fa-arrow-right></i>', inputValidator: function (result) { return new Promise(function (resolve, reject) { if (result) { resolve() } else { reject('You need to agree with T&C') } }) } }).then(function (result) { swal({ type: 'success', text: 'You agreed with T&C :)' }) }) |
|
file |
swal({ title: 'Select image', input: 'file', inputAttributes: { accept: 'image/*' } }).then(function (file) { var reader = new FileReader reader.onload = function (e) { swal({ imageUrl: e.target.result }) } reader.readAsDataURL(file) }) |
|
range |
swal({ title: 'How old are you?', type: 'question', input: 'range', inputAttributes: { min: 8, max: 120, step: 1 }, inputValue: 25 }) |
Non sono supportati più input, è possibile raggiungerli utilizzando i
parametri html e preConfirm.
All'interno della funzione preConfirm() puoi passare il
risultato personalizzato alla funzione resolve() come
parametro:
swal({ title: 'Multiple inputs', html: '<input id="swal-input1" class="swal2-input">' + '<input id="swal-input2" class="swal2-input">', preConfirm: function () { return new Promise(function (resolve) { resolve([ $('#swal-input1').val(), $('#swal-input2').val() ]) }) }, onOpen: function () { $('#swal-input1').focus() } }).then(function (result) { swal(JSON.stringify(result)) }).catch(swal.noop) |
Method | Description |
---|---|
swal.isVisible() | Determine if modal is shown. |
swal.setDefaults({Object}) | If you end up using a lot of the same settings when calling SweetAlert2, you can use setDefaults at the start of your program to set them once and for all! |
swal.resetDefaults() | Resets settings to their default value. |
swal.close() or swal.closeModal() | Close the currently open SweetAlert2 modal programmatically. |
swal.enableButtons() | Enable "Confirm" and "Cancel" buttons. |
swal.getTitle() | Get the modal title. |
swal.getContent() | Get the modal content. |
swal.getImage() | Get the image. |
swal.getConfirmButton() | Get the "Confirm" button. |
swal.getCancelButton() | Get the "Cancel" button. |
swal.disableButtons() | Disable "Confirm" and "Cancel" buttons. |
swal.enableConfirmButton() | Enable the "Confirm"-button only. |
swal.disableConfirmButton() | Disable the "Confirm"-button only. |
swal.showLoading() or swal.enableLoading() | Disable buttons and show loader. This is useful with AJAX requests. |
swal.hideLoading() or swal.disableLoading() | Enable buttons and hide loader. |
swal.clickConfirm() | Click the "Confirm"-button programmatically. |
swal.clickCancel() | Click the "Cancel"-button programmatically. |
swal.showValidationError(error) | Show validation error message. |
swal.resetValidationError() | Hide validation error message. |
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.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.getProgressSteps() | Progress steps getter. |
swal.setProgressSteps([]) | Progress steps setter. |
swal.showProgressSteps() | Show progress steps. |
swal.hideProgressSteps() | Hide progress steps. |