Welcome Folks I am back with another interesting post. In this post we will be talking about a Awesome Library for making Plain old Javascript Popups more interactive and appealing. The library name is SweetAlert2. It’s a Open Source Library and you can use this library in your projects to replace the old fashion popups.
1 |
alert('You clicked the button!') |
1 2 3 4 5 |
Swal.fire( 'Good job!', 'You clicked the button!', 'success' ) |
Download and Install
1 |
npm install sweetalert2 |
Grab from jsdelivr CDN
1 |
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script> |
Usage
1 2 3 |
<script src="sweetalert2.all.min.js"></script> <!-- Optional: include a polyfill for ES6 Promises for IE11 and Android browser --> <script src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script> |
You can also include stylesheet and js files separately
1 2 |
<script src="sweetalert2.min.js"></script> <link rel="stylesheet" href="sweetalert2.min.css"> |
1 2 3 4 5 |
// ES6 Modules or TypeScript import Swal from 'sweetalert2' // CommonJS const Swal = require('sweetalert2') |
1 2 3 |
import Swal from 'sweetalert2/dist/sweetalert2.js' import 'sweetalert2/src/sweetalert2.scss' |
Call Swal function after Page has been loaded
1 2 3 4 5 6 |
Swal.fire({ title: 'Error!', text: 'Do you want to continue', type: 'error', confirmButtonText: 'Cool' }) |
SweetAlert 2 Mixin Example
1 2 3 4 5 6 7 8 9 10 11 |
const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 }); Toast.fire({ type: 'success', title: 'Signed in successfully' }) |
Popups Alert Types
Error
Warning
Info
Success
Question
Examples
Input Alert Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const ipAPI = 'https://api.ipify.org?format=json' 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}`) } |
Input Email Alert Popup
1 2 3 4 5 6 7 8 9 |
const {value: email} = await Swal.fire({ title: 'Input email address', input: 'email', inputPlaceholder: 'Enter your email address' }) if (email) { Swal.fire('Entered email: ' + email) } |
Input URL Alert Popup
1 2 3 4 5 6 7 8 |
const {value: url} = await Swal.fire({ input: 'url', inputPlaceholder: 'Enter the URL' }) if (url) { Swal.fire('Entered URL: ' + url) } |
Password Input Alert Popup
TextArea Input Alert Popup
1 2 3 4 5 6 7 8 9 |
const {value: text} = await Swal.fire({ input: 'textarea', inputPlaceholder: 'Type your message here...', showCancelButton: true }) if (text) { Swal.fire(text) } |
Select Alert Input Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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) => { if (value === 'oranges') { resolve() } else { resolve('You need to select oranges :)') } }) } }) if (fruit) { Swal.fire('You selected: ' + fruit) } |
Radio Button Input Alert Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// inputOptions can be an object or Promise 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}) } |
Checkbox Input Alert Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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-right></i>', inputValidator: (result) => { return !result && 'You need to agree with T&C' } }) if (accept) { Swal.fire('You agreed with T&C :)') } |
File Input Alert Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const {value: file} = await Swal.fire({ 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) } |
Range Input Alert Popup
1 2 3 4 5 6 7 8 9 10 11 |
Swal.fire({ title: 'How old are you?', type: 'question', input: 'range', inputAttributes: { min: 8, max: 120, step: 1 }, inputValue: 25 }) |
Multiple Inputs Alert Popup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const {value: formValues} = await 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)) } |
More Examples
1 2 3 4 5 6 |
Swal.fire({ type: 'error', title: 'Oops...', text: 'Something went wrong!', footer: '<a href>Why do I have this issue?</a>' }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Swal.fire({ title: '<strong>HTML <u>example</u></strong>', type: 'info', html: 'You can use <b>bold text</b>, ' + '<a href="//github.com">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', }) |
1 2 3 4 5 6 7 |
Swal.fire({ position: 'top-end', type: 'success', title: 'Your work has been saved', showConfirmButton: false, timer: 1500 }) |
1 2 3 4 5 6 7 |
Swal.fire({ title: 'Custom animation with Animate.css', animation: false, customClass: { popup: 'animated tada' } }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Swal.fire({ 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((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' ) } }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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!", type: '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 result.dismiss === Swal.DismissReason.cancel ) { swalWithBootstrapButtons.fire( 'Cancelled', 'Your imaginary file is safe :)', 'error' ) } }) |
1 2 3 4 5 6 7 8 9 |
Swal.fire({ title: 'Sweet!', text: 'Modal with a custom image.', imageUrl: 'https://unsplash.it/400/200', imageWidth: 400, imageHeight: 200, imageAlt: 'Custom image', animation: false }) |
1 2 3 4 5 6 7 8 9 10 11 12 |
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 left no-repeat ` }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let timerInterval Swal.fire({ title: 'Auto close alert!', html: 'I will close in <strong></strong> seconds.', timer: 2000, onBeforeOpen: () => { Swal.showLoading() timerInterval = setInterval(() => { Swal.getContent().querySelector('strong') .textContent = Swal.getTimerLeft() }, 100) }, onClose: () => { clearInterval(timerInterval) } }).then((result) => { if ( // Read more about handling dismissals result.dismiss === Swal.DismissReason.timer ) { console.log('I was closed by the timer') } }) |
1 2 3 4 5 6 7 8 9 10 11 |
Swal.fire({ title: 'هل تريد الاستمرار؟', type: 'question', customClass: { icon: 'swal2-arabic-question-mark' }, confirmButtonText: 'نعم', cancelButtonText: 'لا', showCancelButton: true, showCloseButton: true }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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 }) } }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Swal.mixin({ input: 'text', confirmButtonText: 'Next →', 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) { Swal.fire({ title: 'All done!', html: 'Your answers: <pre><code>' + JSON.stringify(result.value) + '</code></pre>', confirmButtonText: 'Lovely!' }) } }) |