How to create beautiful and custom JavaScript alerts using SweetAlert.JS

in #utopian-io7 years ago (edited)

What Will I Learn?

  • You will learn about SweetAlert JavaScript library
  • You will learn how to setup SweetAlert library on your website
  • You will learn how to create beautiful alerts using SweetAlert library

Requirements

  • Basic HTML and CSS knowledge is required
  • Basic JavaScript knowledge is required
  • You need a Text Editor, web browser and internet connection to download some resources if necessary.

Difficulty

  • Basic

Tutorial Contents

Introduction

SweetAlert is an open source project javascript library that allows designers to replace default javascript alert with a more advanced and beautiful one. SweetALert makes popups and modals messages look pretty and easy to configure even for beginners.

SweetAlert JavaScript library is very easy to use and can help modernize the default boring JS alert we are used to customizable and beautiful ones.

For this tutorial, we’re going to setup a simple webpage to showcase the work of SweetAlert JavaScript library while also showing the default JS alert alongside it. We’ll create two buttons, one will demonstrate SweetAlert and the other one Defualt JS alert.

FINAL RESULT

image.png

STEPS

Setup web page

We need to follow the following steps below to create our web page;

  1. Launch your text editor and create a new file and save it as "sweetalert.html" in your development folder.
  2. Write down the standard HTML5 tags used in defining a HTML document in "sweetalert.html" file. Example;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Utopian-io – Beautiful and sweet JavaScript alerts using SweetAlert.JS</title>
  </head>
<body>
    
</body>
</html>

Installing SweetAlert.JS

In order to integrate SweetAlert.JS into our page. We have to download the library from the official repo here or we can make use of the available sweetalert CDN links. For this tutorial, we’re going to use CDN link but it’s recommended that make use of local copy for production purpose.
We only need the sweetalert JS CDN link for it work;

JS

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

NB: The additional CSS and JS links are that of bootstrap. Our work does not depend on it but if you’re still interested you can download it here and link it to your work.

image.png

Setup SweetAlert.JS:

  1. Locate the <body> section in "sweetalert.html" and create two buttons with onclick attribute like the one below. The classes are that of bootstrap.
<button class="btn btn-lg btn-primary" onclick="sweetAlert()">SweetAlert</button>
<button class="btn btn-lg btn-success" onclick="defualtAlert()">DefaultAlert</button>
  1. Scroll down to the bottom of the file immediately after the last <script> tag and before the </body> and write down the following code snippets to initiate and configure SweetAlert.

Default JS Alert

function defualtAlert() {
      alert("I'm a boring and ugly Alert!");
    }

Preview in browser

Screenshot below shows the default JS Alert after clicking the green button.

image.png

SweetAlert

function sweetAlert() {
      swal("What do you want to do?", {
        buttons: { //creates a button. You can separate them with a comma.
          cancel: "Cancel!", 
          catch: {
            text: "Submit!",
            value: "catch",
          },
          register: true,
          try: true,
        },
      })
      .then((value) => {
        switch (value) { //creates a switch inbetween the buttons we created above.
       
          case "register":
            swal("Type username here:", {
              content: "input", //content is an option which describe the content of the modal
            })
            .then((value) => {
              swal(`Your username is: ${value}`);
            });
            break;
       
          case "catch":
            swal("Yaay!", "Registered successfully!", "success");
            break; 

          case "try": // this is a confirm function in sweetalert
          swal("Are you sure?", {
            dangerMode: true, //this option setup a confirm modal in sweetalert.
            buttons: true,
          });    
          break;     
        }
      });
    }
Code Explanation

There are comments beside the options/methods used in the codes for clarification and explanation. This function sweetAlert() will trigger the sweetalert function created. Swal function is a global function that is use when working with sweetalert. The second part of the code creates a switch to handle the various buttons operations we created. Some of the options used are;

  • Button: creates a button. You can hide default button in a modal using hide and can change the name when it’s set to string.
  • Contents: gives option to set the content of modal, it can be input like we used here or more advanced like attaching an attribute to the input and lots more.
  • dangerMode: if it’s set to true the confirm button will be red and focus will be on the default cancel button.
    These are just some of the options and methods we can use in SweetAlert library. You can check the official documentation for more
    DEMO OF FINAL RESULT in GIF

    sweetalert.gif

Source code

The full source code of this tutorial can be found in my JSFiddle Account

Curriculum

Some of my previous works are;

  1. How to Create a Spreadsheet component using HTML5 and JavaScript
  2. How to introduce new feature to users of your application using Bootstrap Tour
  3. How to Create a quick and beautiful landing page using Bootstrap-4



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • Official installation Tutorial has everything you want to contribute for the project. (Even with the instant preview options)
  • Not necessarily a must but i would recommend you to stand what you wrote as in giving examples via your own suggestions like

"In order to integrate SweetAlert.JS into our page. We have to download the library from the official repo here or we can make use of the available sweetalert CDN links. For this tutorial, we’re going to use CDN link but it’s recommended that make use of local copy for production purpose."

  • Than don't use

script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js">

  • Also use this part only if the ones that are related and a must to acknowledge current contribution of yours, (We don't expect to have some of your previous works at this part. We don't really require a resumee from anyone to contribute.)

43.jpg

Kind Regards

You can contact us on Discord.
[utopian-moderator]

Okay, noted. Thank you!

Hey @ewq, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Coin Marketplace

STEEM 0.17
TRX 0.16
JST 0.029
BTC 62213.63
ETH 2420.81
USDT 1.00
SBD 2.59