trigger sweet alert through javascript

How to Trigger Sweet Alert through Javascript

If you want to add some alert or notification to your website or web application, Sweet Alert is a great option to consider. It's a customizable and easy-to-use library that can help you display beautiful alerts and modals on your site. Here's how you can trigger a Sweet Alert through JavaScript:

Step 1: Include Sweet Alert in your HTML file

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
</body>

You'll need to include both the CSS and JavaScript files for Sweet Alert in your HTML file. You can either download the files and host them on your server or use a CDN, as shown in the example above.

Step 2: Write the JavaScript code to trigger the Sweet Alert

swal("Hello world!");

The code above will display a simple alert with the message "Hello world!". You can customize the alert by passing more options to the swal() function, such as the title, text, icon, buttons, and more. Here's an example with more options:

swal({
  title: "Are you sure?",
  text: "You won't be able to revert this!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
    swal("Poof! Your file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your file is safe!");
  }
});

This code will display a warning alert with a message and two buttons ("Cancel" and "Delete"). If the user clicks the "Delete" button, another success alert will be displayed with a different message. If the user clicks "Cancel" or closes the alert, nothing happens.

<button onclick="swal('Hello world!')">Click me</button>

You can trigger the Sweet Alert from a button or link by adding the onclick attribute and passing the swal() function with the desired options as shown above.

There are many other ways to trigger Sweet Alert through JavaScript, such as using setTimeout(), event listeners, or AJAX requests. The key is to use the swal() function and pass the appropriate options to customize your alerts.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe