Sweetalerts - Beautiful Alerts

Alerts have been a major part of a developer's life. Be it from testing code flow in the development or telling a user that he has entered a wrong password in production, alerts have come a long way. But with an alert, comes the great problem:

  1. Styling: You cannot style an alert box and the default alert shown by the user might not go along with your current UI.
  2. Different browsers show alerts at different positions.
  3. Some browsers are also blocking alerts to prevent spam.

I don't think using simple alerts would be safe with these problems, but we also want to show meaningful alerts to our users. To solve this, we can use SweetAlerts or more precisely, SweetAlerts2. They provide us with beautiful, responsive, and customizable alerts. Yes, you got that write, beautiful and customizable. The default alert shown by sweetalert is really cool and above that, you can add your custom CSS to style them. SweetAlert2

Using SweetAlert: Sweetalert provides very user-friendly docs and nice examples covering all the different things which you can do with it.

The best features of sweetalert, which I like the most are :

  1. Adding functionality to buttons: You can use simple JS to perform different actions based on whether the user has agreed with whatever you mentioned in the alert or not. The simple code for this would look something like this :
Swal.fire({
  title: 'Do you like this blog?',
  showDenyButton: true,
  showCancelButton: true,
  confirmButtonText: `Yes`,
  denyButtonText: `Nope!`,
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire('Thank you so much!')
  } else if (result.isDenied) {
    Swal.fire("Comment below and tell me how I can improve.)
  }
})

In the above code, the user has prompted a question "Do you like this blog?". Now, the user has three choices, either he says "yes", a "no" or refuses to answer and closes the alert. And we have exactly covered this by using isConfirmed and isDenied.

  1. You can embed HTML too in the sweetalert.
Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  icon: 'info',
  html:
    'You can use <b>bold text</b>, ' +
    '<a href="//sweetalert2.github.io">links</a> ' +
    'and other HTML tags',
 })

So you can give different headings, bold and italics text, and all other things which make your alert really powerful.

  1. Adding CSS to your alert: This is one of the most powerful features. Adding CSS means the alert is now completely yours. Personalize it for your website and give your user an alert that doesn't irritate him but rather catches his attention. You can use the set customClass option to set a class name for your alert and style it using CSS.

So this was all for SweetAlerts. Make sure you give it a try and let me know if it was helpful to you or not.