How to use SweetAlert | Ludu

How to use SweetAlert

by Tristan Edwards Tristan Edwards

58 thanks

  • SweetAlert is an easy-to-use library that aims to replace JavaScript's existing "alert" and "prompt" features with better-looking versions. In this lesson, we'll go through the basics and common use cases of the library.

    +
  • Installing

    +
  • Let's first create a project folder called sweetalert-tests (you can put it wherever you prefer) where we'll keep all of our files.

    +
  • In this tutorial, we'll just place the folder on our Desktop
    +
  • If you have Bower (http://bower.io) or NPM (https://www.npmjs.com) installed on your computer, getting SweetAlert can be done through a single line in your terminal.

    +
  • Loading code...
    +
  • This way, all the SweetAlert files will automatically be added to your project in either "bower_components" or "node_modules". If you prefer to install it manually you can download a zip-file directly from the website, or use a CDN, such as https://cdnjs.com/libraries/sweetalert.

    +
  • Now create a brand new HTML file called index.html in the root of your project and open it with your favorite text editor. In it, we'll just put some very basic markup,  reference the SweetAlert-files, and create a simple "Hello world!"-modal.

    +
  • Loading code...
    9
    Tristan Edwards
  • Now go back to the terminal, make sure you're in your project directory, and open a simple HTTP server. If you're on a Mac, you can use Python for this:

    +
  • Loading code...
    2
    Tristan Edwards Jun Pan
  • If you now visit localhost:5000 in your browser, you should see the SweetAlert appear. Magic! If you're having trouble with the HTTP server, you could also just open the index.html file directly in your browser.
    +
  • You can also use the shorthand swal() instead of sweetAlert(), which is much faster to type. Now that you've got the basics set up, let's go through some more advanced examples of what you can use SweetAlert for!

    +
  • Displaying error messages

    +
  • The obvious first use case for SweetAlert is to display generic error messages to the user. For this, SweetAlert has a built-in "error"-type that you can pass as the third function argument:

    +
  • Loading code...
    +
  • Reload the page and you should see this!
    +
  • That is the short way of adding the three most common arguments (title, text and type). There is also a longer version where you pass in a JavaScript object instead with the following keys:

    +
  • Loading code...
    +
  • By using the longer version, you can pass in other options to customize the look of your SweetAlert. Check out the documentation (http://tristanedwards.me/sweetalert) to see all the available keys.

    +
  • Display a warning for a dangerous action

    +
  • When a user on your site is about to do something dangerous, it's usually good to display a warning first to make sure they want to go through with the action.

    +
  • In this example, we'll simulate what would happen is a user tries to delete one of their photos on your website.
    We will first display a warning with two options: "Delete" and "Cancel".
    If the user clicks on "Delete", we will send an AJAX request to a specific URL, and based on the response we'll show a new SweetAlert either of type "success" or of "error".

    +
  • We're going to use jQuery here just to make the code a little simpler and more readable, so make sure you include a link to it in your <head> first!

    +
  • Loading code...
    +
  • One of the keys we'll use is confirmButtonColor, to make the Confirm-button red (since we want to signal danger). 
    Also, in order to follow typical REST conventions, we are sending a DELETE request to /api/photos/{photo_id} when you click that button. The final code in your body should therefore look something like this:

    +
  • Loading code...
    +
  • The customized modal appears when you click the "Delete photo" button!
    +
  • Now don't worry if you see the "We couldn't connect to the server!" error message when you click on "Yes, delete it". This is normal.
    Remember that this is just an example of how it should work, but we don't actually have any API in place for this project.

    +
  • Normally you would write your API in a server-side language such as Node.js or PHP and just return status 204 (no content) once you've removed the file. If you do that, then a new SweetAlert modal will confirm that the file has indeed been deleted.

    +
  • Follow an external link

    +
  • Another common use case is that you want to warn your users before they visit a link on another site. The way we could do this is to attach an event to all the anchor tags in our document, and hijack the process with SweetAlert (again, we're using jQuery):

    +
  • Loading code...
    +
  • Works great!
    +
  • Ask for a user's password

    +
  • Since version 0.5.0, you can also use SweetAlert as a replacement for the prompt-modal.

    +
  • A common thing to do is to ask a user for their password, validate it, and then send a request. Imagine that a user wants to delete their account, and you first ask them for their password to make sure they are who they claim they are.

    +
  • Let's first create a simple SweetAlert where we just ask for the password and log it in the console!

    +
  • Loading code...
    +
  • Now go to your browser, click "Delete my account" and you should see something like this: 

    +
  • Awesome!
    +
  • Now, open up the JavaScript console in the browser. If you're using Chrome, this is in View -> Developer -> JavaScript Console. Type something in the input field, then click OK, and you should see the password being logged:

    +
  • Not exactly the most secure password, but you get the point...
    +
  • That's nice and all, but let's take it one step further! We want to be able to validate the password directly. If it's correct we want to send an AJAX request somewhere, and if not, we want to show an error to the user.

    +
  • Thankfully, SweetAlert has a built-in function for displaying error messages on the input as well (swal.showInputError), so let's tweak that callback function!

    +
  • Loading code...
    +
  • That was easy wasn't it? Now if you click "OK" with the input field left blank you will get a message saying "You need to type in your password in order to do this!".

    +
  • And if you did type in your password, we will send an AJAX request to the (non-existant) API, and if it returns an error (which it will always do here), then that means that the password was wrong and you will see this:

    +
  • Pretty nice functionality with so few lines of code!
    +
  • Final words

    +
  • As you can see, it's simple to get the small overlooked features to look really good with SweetAlert. These are just a few examples, but SweetAlert is very flexible so there is of course lots more you can do! As always, the best thing to do is just to play around.

    +
  • If you liked this lesson, don't hesitate to click the "Thank"-button below, and feel free to contribute to SweetAlert on its GitHub repo!

    +

Did it help you? Click to say "thanks" to the author!

Want to create your own course on Ludu?

Back to lesson