How to use sweetalert2
By FoxLearn 3/19/2020 11:40:48 AM 9.57K
Sweetalert2 is a beautiful popup boxes helps you easily show a message box in your website.
You can download and install Sweetalert2 at github
or you can download it directly from cdnjs in your Visual Studio.
Right-clicking on your folder you need to install, then select Add =>Client-Side Library...
Creating a html page, then modify your code as shown below.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="lib/limonte-sweetalert2/sweetalert2.min.css" /> </head> <body> <button class="btn btn-primary" aria-label="Try me! Example: A basic message" onclick="message()"> Try me! </button> <script src="lib/jquery/dist/jquery.min.js"></script> <script src="lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="lib/limonte-sweetalert2/sweetalert2.all.min.js"></script> <script type="text/javascript"> function message() { 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' ) } }); } </script> </body> </html>
If you want to show a basic message you can modify your message function as shown below.
Swal.fire('Welcome to FoxLearn !')
Sweetalert2 display a title with a text under
Swal.fire( 'Enter your title', 'Enter your message', 'question' )
Sweetalert2 display a modal with a title, an error icon, a text, and a footer
Swal.fire({ icon: 'error', title: 'Enter your title here', text: 'Enter your message here', footer: '<a href>http://foxlearn.com</a>' })
Sweetalert2 display a modal window with a long content inside
Swal.fire({ imageUrl: 'Your image url', imageHeight: 1500, imageAlt: 'Your alt image' })
Sweetalert2 with a custom HTML description and buttons with ARIA labels
Swal.fire({ title: 'Your html title', icon: 'info', html: 'Your html content', showCloseButton: true, showCancelButton: true, focusConfirm: false, confirmButtonText: 'Your html button text', confirmButtonAriaLabel: 'Thumbs up', cancelButtonText:'Your html button text', cancelButtonAriaLabel: 'Thumbs down' })
Sweetalert2 with a custom positioned dialog
Swal.fire({ position: 'top-end', icon: 'success', title: 'Your work has been saved', showConfirmButton: false, timer: 1500 })
Sweetalert2 with custom animation with Animate.css
Swal.fire({ title: 'Custom animation with Animate.css', showClass: { popup: 'animated fadeInDown faster' }, hideClass: { popup: 'animated fadeOutUp faster' } })
Sweetalert2 display a confirm dialog, with a function attached to the "Confirm"-button
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' ) } })
Sweetalert2 passing a parameter, then you can execute something else for "Cancel"
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' ) } })
Sweetalert2 display a message with a custom image
Swal.fire({ title: 'Sweet!', text: 'Modal with a custom image.', imageUrl: 'https://unsplash.it/400/200', imageWidth: 400, imageHeight: 200, imageAlt: 'Custom image', })
Sweetalert2 display a message with custom width, padding, background and animated Nyan Cat
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 ` })
Sweetalert2 display a message with auto close timer
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') } })
Sweetalert2 with Right-to-left for Arabic, Persian, Hebrew, and other RTL languages
Swal.fire({ title: 'هل تريد الاستمرار؟', icon: 'question', iconHtml: '؟', confirmButtonText: 'نعم', cancelButtonText: 'لا', showCancelButton: true, showCloseButton: true })
Sweetalert2 AJAX request example
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 }) } })
Sweetalert2 chaining modals (queue) example
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) { const answers = JSON.stringify(result.value) Swal.fire({ title: 'All done!', html: ` Your answers: <pre><code>${answers}</code></pre> `, confirmButtonText: 'Lovely!' }) } })
Sweetalert2 Dynamic queue example
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' }) }) } }])
As you know, sweetalert2 is the 34th most popular package on jsDelivr.
- How to Add Active Navigation Class Based on URL
- How to Display popup message in Javascript
- How to Show message instead of alert
- How to fix 'Uncaught TypeError: Cannot read property 'fn' of undefined'
- How to Format numbers with commas in Javascript
- How to format number with commas and decimal in Javascript
- How to Pass string parameter in an onclick function
- How to get @Url.Action url in a separate script file?