Purpose of alerts
A demo to create and trigger simple alert
In this demo, a simple alert is created by using the alert keyword. As you click the button, the alert will be shown. See the demo and code online:
An alert with a variable value
This is a useful feature for developers as well for debugging applications (apart from other option, of course).
See a demo online:
You see, I simply used variable name inside the alert without double quotes:
var alertstr = "Variable used in alert";
Similarly, you may concatenate a variable with a string by using operator as shown below:
alert(“Alert with concatenation: ” + alertstr);
Creating fancy alerts
All the alerts in above examples are using the default browser-based style that is considered boring and old-fashioned.
A basic alert demo by using a plug-in
In this demo, I have used a plug-in, SweetAlert, which is available at the Github website. This plug-in is quite simple to use. First have a look at a few demos of different alerts by using it.
See a basic alert demo online by using SweetAlert:
You can see, instead of using “alert” keyword in the <script> section, I just used “swal” to create a basic alert with a message and “Ok” button to close it.
An alert with success and animation
See a demo and code online for this alert:
See online demo and code
The complete JS function code is:
swal("Congrats!", ", Your account is created!", "success");
This function is called at the click event of the button.
You may show this alert after filling the form by the user and upon successful entry into the database.
You may use this alert type for giving a warning to the user before proceeding to some critical action like “deleting an account permanently” or deleting a file etc.
See the demo online with code:
You can see, a user is presented with a confirmation alert with Red button to proceed or cancel the operation. In each case, the related message is shown in next alert with an Ok button to close the alert. You may perform an action there rather showing alerts.
A prompt alert example
In this demo, a prompt alert is shown to take the user input before proceeding. See the demo online:
Setting up this cool plug-in
In order to use SweetAlert plug-in in your website, you simply need to include two dependency files in the <head> section of your webpage:
<script src=” sweetalert-dev.js”></script>
<link rel=”stylesheet” href=” sweetalert.css”>
Get the files from the GitHub website. You may place these files in folders as per your project specifications. The downloaded package contains many other files but only two files are required as mentioned earlier and used in demos.