SweetAlert2 – Working with Nice Alert’s

Hello guys, after a long time, today i’m going to introduce SweetAlert, first of all let me tell you guys that SweetAlert is a Library made with JavaScript and CSS, that act’s as a replacement for default JavaScript’s dialog, pop-ups and modal window as well, SweetAlert shows very impressive and pretty modal windows and as you all know that default JavaScript dialog looks ugly and terrible in terms of UX/UI and if you are working on any project that needs more user attraction then you must try this out. SweetAlert allows you to create attractive and pretty JavaScript dialogs like alert, confirm, prompt, and modal windows very quickly. So we have SweetAlert then you should avoid using default JavaScript Pop-Up’s and i recommend you to use SweetAlert for your projects and for that you just need to add JavaScript and CSS file in your page, Ok we discussed that what is SweetAlert now move ahead to next step, so let’s have a look how to use it.

SweetAlert2 : A Beautiful Replacement for JavaScript Alerts

Read : Bootstrap Confirm Delete Dialog Box

Let’s Start

Now let’s see how to use and getting started with this awesome and easy to use library, To use SweetAlert in your projects you just have to Download it from GitHub.

Note : SweetAlert plugin is now inactive so you should use SweetAlert2, or if you are already using sweetalert then you should migrate to (SweetAlert2)Swal2.

once downloaded, place the CSS and JS files link within your page where you want to show alert’s.

Add Sweet CSS
add the sweetalert css file within document’s <head> tag.


<link rel="stylesheet" href="path/to/sweetalert2.min.css">

Add Sweet JS
once css added, you have to add JavaScript file just before closing </body> tag.

<script src="path/to/sweetalert2.min.js"></script>

Of course you need a jQuery library too, here it is.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Use of SweetAlert CDN
if you want to use CDN, head over to the following links and use them.

https://cdnjs.com/libraries/limonte-sweetalert2
https://www.jsdelivr.com/projects/sweetalert2

All set, now you can create awesome alerts with this Sweet library, Have a look.

Sample Code

This is short and simple code contains one “click me” button and very short swal(‘Simpel Alert’); Alert calling method.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sweet Alert - Example</title>
<link rel="stylesheet" href="dist/sweetalert2.min.css">
</head>
<body>    
    
<button type="button">Click me</button>        

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="dist/sweetalert2.min.js"></script>        

<script>
$(document).ready(function(){
      /* Call Simple Alert on Button Click  */
     $('button').click(function(){            
          sweetAlert('Simpel Alert');   
          // or can be swal('Simpel Alert');
     });
})
</script>        
</body>
</html>

Here in above example i have taken only one button to trigger simpel SweetAlert, we can also use shorthand function swal(“Simple Alert Goes Here…”) to call SweetAlert

Here’s how a simple alert looks created with SweetAlert.

SweetAlert2 : Simple Alert Example

In above example i take only one parameter as a message, but for the various stages we can use three parameters and it accepts upto three parameters.

  • Title : Title of alert box.
  • Text : Message of alert box.
  • Type : Type of modals you want to show with success, info, warning,error and question

Let’s See More…

now let’s have a look some more examples of SweetAlert.

Success Alert :

swal(
   'Awesome !',
   'Form Submitted Successfully!',
   'success'
);

as i just said that it can be used with three parameters title, text and type so it can be also written as folowing by passing the object as the first parameter.

swal({
   title: 'Awesome !',
   text: 'Form Submitted Successfully !',
   type: 'success'
});

It can be also written as :

swal('Awesome !', 'Form Submitted Successfully!', 'success');

See the following demo on CodePen, It will alert’s like this :

See the Pen SweetAlert-Success by Pradeep Khodke (@pradeepkhodke) on CodePen.


now you can show awesome alert’s as your need like success, info, warning and error you just have to change title text and type that’s it.

Confirm :
as you all know that getting confirmation is important before doing(deleting) any process, so SweetAlert has much prettier confirm modal, for that you can use ajax for the rest process.

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'
  );
})

See the Pen SweetAlert-Confirm by Pradeep Khodke (@pradeepkhodke) on CodePen.


as you can see few more parameters in the given example showCancelButton, confirmButtonColor and confirmButtonText hope i don’t need to explain it in detail, you will get idea by parameter names that what can they do and then within function you can show success message.

Ajax Request with SweetAlert

You can also handle $.ajax() requests with sweetalert by using following code.

swal({
    title: 'Are you sure?',
    text: "You won't be able to revert this back!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!',
    showLoaderOnConfirm: true,
    preConfirm: function() {
        return new Promise(function(resolve) {
       /*
    Handle Ajax Request Here...
    */
        });
    },
    allowOutsideClick: false      
});

in this example few parameters are, i just mentioned above but there’s a new preConfirm can be used to handle ajax requests, you can use it for getting confirmation alert before deleting mysql data from table and allowOutsideClick parameter allows you to disable outside click when alert is active means it cannot be cancelled by clicking outside of alert dialog and it can be true/false.

you can also show HTML content and Image within alerts and it can be also animated using Animate.css library.

Input Types

However it supports all the HTML Input types like text, email, password, select, textarea, radio. i am not going to show all the example cause post could become quite longer so let’s take email input example.

swal({
  title: 'Enter email address',
  input: 'email'
}).then(function (email) {
  swal({
    type: 'success',
    html: 'Your email: ' + email
  })
})

CodePen Demo Output :

See the Pen SweetAlert : Input Email by Pradeep Khodke (@pradeepkhodke) on CodePen.

well, this is just a short tutorial about SweetAlert that i have covered here to just introduce you this awesome library, you can find lot’s more examples on official site so go ahead and try so that you can achieve very impressive awesome and much pretty functionality with the just few lines of code.

that’s it, for the day, if you liked this tutorial then please don’t forgot to share with your on/off line friends and feel free to ask any query regarding any of the tutorial.

Happy Coding 🙂